Home > Enterprise >  WordPress - Dynamically add user ID to the end of a URL
WordPress - Dynamically add user ID to the end of a URL

Time:05-14

I'm looking for a way to have the current logged in username added to the end of a link.

example: www.mywebsite.com/custom-post-type/author-post-title

"author-post-title" would be replaced with the current logged in username

This link will lead to a private post that is automatically created using Gravity Forms. The post title is the same as the logged-in person's username. I would like this link to be in place dynamically beforehand. Each author is limited to only one post and users already have to be logged in to see the link in nav menu.

I'm thinking there is a way to code this where the author name is a placeholder and is replaced by the currently logged in user ID, but I have not been able to figure it out. Something like... but this is way off as I am new to php.

<?php

function replace_text($text) {
    $text = str_replace('author-post-title', '$user_id', $text);
    $user_id = get_current_user_id();
    return $text;
}

?>

CodePudding user response:

I would recommend you to make generic page which has same URL for all users and modify it's content for specific user. It will be easier to attach this link to nav menu.

But, if you really need to create this kind of link you may create it using function:

function get_user_specific_url() {
    if ( is_user_logged_in() ) {
        return sprintf(
            '%s/custom-post-type/%s',
            get_site_url(),
            wp_get_current_user()->user_nicename
        );
    }

    // Redirect home in case if not logged in
    return get_site_url();
}

Then you may want to create custom rewrite rule for this link structure to display specific page for user:

add_action( 'init', function() {
       add_rewrite_tag("%user_nicename%", '([^/]*)');
       add_rewrite_rule(
           '^custom-post-type/([^/]*)/?',
           'index.php?page_id=123&user_nicename=$matches[1]',
           'top'
       );
} );

CodePudding user response:

You could try adding the following shortcode to your page: [replace_link_w_user link="add your link here without username" button="Add button text here"]

Then add the following to your functions.php:

add_shortcode( 'replace_link_w_user', 'rl_w_user' );
function rl_w_user($atts = array()) {
    $details = shortcode_atts( array(
        "link"=>'',
        "button_text"=>'Search'
    ), $atts );
    if ( is_user_logged_in() ) {
        $button='
        <form action="'.$details['link'].'/'.wp_get_current_user()->user_nicename.'">
            <input type="submit" value="'.$details['button_text'].'" />
        </form>';
        return $button;
    } else {
       return;
    }
}
  • Related