0

I've created a quick function and shortcode to allow me to include logged-in user only content:

function content_for_logged_in($atts,$content){
    $logged_in_content = "";
    if(is_user_logged_in()){
        $logged_in_content = $content;
    }
    return $logged_in_content;  
}
add_shortcode('logged-in-content','content_for_logged_in');

But it doesn't parse shortcodes that are within the content, e.g.:

[logged-in-content]
<p>Some test content...</p>
[wpforms id="752"]
[/logged-in-content]

...in this case, the wpforms shortcode is displayed rather than the form.

Is there a way to alter my function so that shortcodes within the content will be parsed?

Thanks, Scott

1

2 Answers 2

1

The function you are looking for is named do_shortcode (there will also be a function apply_shortcode in Wordpress 5.4 that does the same). Codex Page

For your example, this will work:

function content_for_logged_in($atts,$content){
    $logged_in_content = "";
    if(is_user_logged_in()){
        $logged_in_content = do_shortcode($content);
    }
    return $logged_in_content;  
}
add_shortcode('logged-in-content','content_for_logged_in');

Happy Coding!

1
  • Thanks! That's a lot simpler than my "solution" :-)
    – ScottM
    Feb 28, 2020 at 14:13
0

I found a way to achieve what I need right now...

    function content_for_logged_in($atts,$content){
            $logged_in_content = "";
            $embedded_shortcode = $atts['embedded_shortcode'];
            if(is_user_logged_in()){
                $logged_in_content = $content;
                if(!empty($embedded_shortcode)) {
                    $logged_in_content .= do_shortcode('['.$embedded_shortcode.']');
                }
            }
            return $logged_in_content;  
        }

add_shortcode('logged-in-content','content_for_logged_in');

and then this:

[logged-in-content embedded_shortcode="wpforms id=752"]
    <p>Use the form below to upload photos for the Photo Galleries page.</p>
[/logged-in-content]

I’d still be interested if there’s a way to do it so that the actual shortcode can be within the $content area of the enclosing shortcode in case sometime I want to do it so that I can place the embedded shortcode somewhere else within the content, or can do multiple shortcodes within the $content area.

For my immediate needs, the above solution does the trick.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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