0

apologies for the noob post. I'm fairly new to working with wordpress and I want to do my own php functions - here I just want to show the logged in user's firstname on the page. Below is what I added to my theme's functions.php:

add_shortcode('show_name', 'generate_content');
function show_name() {
$current_user = wp_get_current_user();
$first_name = $current_user->user_firstname;
return $first_name;
}

and then I added this to the html editor of the page I want yet it doesn't display anything:

<span style="font-family: 'Josefin Sans', sans-serif; font-size: 20px;">Hi <strong><?php echo do_shortcode("[show_name]"); ?></strong>,</span>

I guess my main questions would be if I wrote the function correctly and/or where should I place the shortcode call. I hope someone could help as I plan to do some more advanced functions (such as updating database values by clicking a button).

0
add_shortcode('show_name', 'generate_content');

When WordPress finds a [show_name] shortcode tag in content, it runs the function that matches the second parameter, which in this case is generate_content. Try renaming your show_name() function to be the same, like this:

add_shortcode('show_name', 'my_show_name_func');
function my_show_name_func() {
    $current_user = wp_get_current_user();
    $first_name = $current_user->user_firstname;
    return $first_name;
}

Everything else looks like it will work though I didn't test this. For more information on adding a shortcode see the WordPress documentation here: https://codex.wordpress.org/Function_Reference/add_shortcode

Also, since you are using it within a php block in a template, you can simply use the php function by calling it directly. For the above example doing this in your template would also work:

... Hi <strong><?php echo my_show_name_func(); ?></strong> ...

Will have the same effect.

Since php functions can be accessed like this, it's best to 'name space' your functions so they - being uniquely named - don't conflict with another function one that uses the same name in another theme or plugin.

Happy coding!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.