John Davidson

php - WordPress - Dynamically add user ID to the end of a URL

0 comments
Message:


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

?>


My Answer:
To dynamically add the current logged in user ID to the end of a URL in WordPress, you can use the following code snippet:

php
$current_user = wp_get_current_user();
$user_id = $current_user->ID;
$url = 'www.mywebsite.com/custom-post-type/author-post-title/' . $user_id;
?>


You can then use the `$url` variable in your template file or wherever you need to display the link with the user ID added at the end.

Please note that this code assumes that the user is logged in and you are using the default WordPress user system. If you are using a custom user system or have specific requirements, you may need to modify the code accordingly.

Rate this post

4 of 5 based on 1206 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us