Question

This code works great when put directly into the content of a page.

<font color=#ff0000> 
<?php global $current_user;
  get_currentuserinfo();

    echo $current_user->display_name . "\n"; 
    echo 'Level: ' . $current_user->level . "\n <br>";

?>
</font>

Result shows 'Sam level 65'

However, when I convert it to a shortcode and try to replace echo with return, wordpress breaks, all screens go blank. This is an example of what i've tried:

// Add Shortcode
function custom_shortcode() {

// Code
<font color=#ff0000> 
<?php global $current_user;
  get_currentuserinfo();

  $output = $current_user->display_name . "\n"; 
  $output .= 'Level: ' . $current_user->level . "\n <br>";

return $output;

?>
</font>
}
add_shortcode( 'userlevel', 'custom_shortcode' );

Any idea where I'm going wrong?

Thank you in advance!

Was it helpful?

Solution

You're using HTML where PHP is expected. That's why you have a blank screen.

Here's how I'd move this into a shortcode:

function wpse_shortcode_userlevel() {
    global $current_user;
    get_currentuserinfo();

    $output = '<span class="shortcode-user-level">';
    $output .= $current_user->display_name . "\n";
    $output .= "Level: {$current_user->level} \n <br>";
    $output .= '</span>';

    return $output;
}
add_shortcode( 'userlevel', 'wpse_shortcode_userlevel' );

Then in your stylesheet add:

.shortcode-user-level {
    color: #ff0000;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top