Adding a template part as part of a shortcode

get_template_part doesn’t return its value, it outputs it, which is how it would normally be used. Think of it this way, how would it know wether to echo the template or return it?

So instead, we use output buffers to catch the output and flush it to a variable, e.g.:

ob_start( );
echo "test";
$output = ob_get_clean();

Further Notes

  • Avoid embedding variables directly in PHP strings like this: "variable: {$variable} " instead use concatenation: " variable:".$variable. It’s not possible to sanitise of escape if you embed in a string directly
  • Shortcodes are a fancy way of calling a function, since you’re in PHP rather than post content, why not skip the middle man and call the function directly?
  • You’ve closed a PHP tag, then reopened it but there’s nothing between the tags, save yourself the effort of typing it out and keep all your PHP together in one block
  • Since you’re only checking if a user is logged in or out, there’s no need for shortcodes and output buffers at all, just use is_user_logged_in() with an if (...) { .... } statement.