skip to Main Content

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;
}

?>

2

Answers


  1. 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'
           );
    } );
    
    Login or Signup to reply.
  2. 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;
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search