Question

I am using "Ultimate Member" plugin to allow users to register because I want some content to be restricted for not signed-in users. According to their documentation, there are a few shortcodes for that and I'm trying to sue one in a template like this:

<?php
    $out_content = get_template_part( 'templates/template-parts/loggedout', 'content' );
    do_shortcode("[um_loggedout] {$out_content} [/um_loggedout]");
?>

<?php
    $in_content = get_template_part( 'templates/template-parts/loggedout', 'content' );
    do_shortcode("[um_loggedin] {$in_content} [/um_loggedin]");
?>

Actually, both template parts are output this way, is this something that can be done?

Was it helpful?

Solution

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.
Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top