Get shortcode from the content and display it in other place (in sidebar, for example)

I have a shortcode: [content_block]

If that shortcode exists in content and has the attribute position=top, I would like to remove it from the content and display it in other place. For example, in sidebar.

In summary:

  • Detect if [content_block] exists
  • If exists, detect if has the attibute position=top
  • If has the attribute, then store the complete shortcode to display it in a different place (for example in the sidebar).
  • And remove it from the content.

How can I do it?

Thanks.

2 Answers
2

You can look to the code WordPress uses for parsing Shortcodes to get some ideas about how to do this. There are a couple of helpful core functions to simplify things.

// our callback function to check for the shortcode.
// this is where you'd put code to set a flag for rendering the shortcode elsewhere
// the complete tag is in $tag[0], which can be passed to do_shortcode later
function wpd_check_shortcode( $tag ){
    if( 'content_block' == $tag[2] ){
        // convert string of attributes to array of key=>val pairs
        $attributes = shortcode_parse_atts( $tag[3] );
        if( array_key_exists( 'position', $attributes )
            && 'top' == $attributes['position'] ){
                // move shortcode to sidebar here
                // return empty to strip shortcode
                return '';
        }
    }
    // return any non-matching shortcodes
    return $tag[0];
}

// source text with shortcode
$text="lorem ipsum [content_block]";

// this generates a regex pattern for all registered shortcodes
$pattern = get_shortcode_regex();

// process all shortcodes through our callback function
$text = preg_replace_callback( "/$pattern/s", 'wpd_check_shortcode', $text );

// modified $text with shortcode removed
echo $text;

Leave a Comment