I'm creating a code that shows the First Name for logged in users, using a shortcode, but I noticed that if the user has no name settle, it will display a blank space. How can I set a custom name to show up instead of the blank space? Something like this "Hi >No Name<, please settle your name in your account."

Display first name:

// show first name if logged in
function colaborador_nome($atts) { if (is_user_logged_in() && !is_feed()) { return '&nbsp;'. get_user_meta( get_current_user_id(), 'first_name', true ); }
add_shortcode('colaborador_nome', 'colaborador_nome'); 

Use PHP ternary comparsion operator to check if get_user_meta() function returns blank or non-blank result:

function colaborador_nome($atts) {
    if (is_user_logged_in() && !is_feed()) {
        return '&nbsp;'. (get_user_meta( get_current_user_id(), 'first_name', true ) ?: "Hi >No Name<, please settle your name in your account.");
add_shortcode('colaborador_nome', 'colaborador_nome'); 
  • I'm sorry, I don't know why, but I posted the wrong code. It's the right code now. Please check. – 023023 Jul 7 '20 at 3:38
  • @21321312 That doesn't make much difference except you should wrap ternary operator with brackets. If you want the full code, here it is. – Ivan Shatsky Jul 7 '20 at 3:50
  • Tried it, it results in a syntax error. – 023023 Jul 7 '20 at 3:57
  • @21321312 It could be only if you copy-pasted this code incorrectly or if you are using PHP version less than 5.3. What is your PHP version? – Ivan Shatsky Jul 7 '20 at 4:08
  • I'm on a localhost using PHP Version 7.2.28. – 023023 Jul 7 '20 at 5:13

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.