The scenario is that I need to add an HTML banner under a slideshow which is a shortcode in the homepage content. I personally hate adding a bunch of div tags to the TinyMCE editor so I’m trying to filter the_content and add my HTML after the specific shortcode. Below is a solution but I wasn’t sure if there was a better way to go about this.

What’s the best way to add content after specific shortcodes?

2 s
2

I wonder if you could override the with this kind of wrapper:

add_shortcode( 'rev_slider', function( $atts = array(), $content="" )
{
    $html="";

    // Your custom banner HTML
    $banner="<div id="bannerHTML"><!-- banner HTML goes here --></div>";

    // Append your banner HTML to the revslider's output
    if( function_exists( 'rev_slider_shortcode' ) )
        $html = rev_slider_shortcode( $atts, $content ) . $banner;

    return $html;

} );

Where we assume that the original shortcode’s callback is rev_slider_shortcode(). We have to run the after the original one.

Update

As suggested by @Sumit we could try to get the shortcode’s callback from the $shortcode_tags array.

Here’s an example:

add_action( 'after_setup_theme', function() use ( &$shortcode_tags )
{
    // Shortcode to override. Edit to your needs
    $shortcode="rev_slider";

    // Nothing to do if it's not registered as shortcode
    if( ! shortcode_exists( $shortcode ) )
        return; 

    // Get the shortcode's callback
    $callback = $shortcode_tags[$shortcode];

    // Override the shortcode
    add_shortcode( $shortcode, function( $atts = array(), $content="" ) use ( $callback )
    {
        // Your custom banner HTML
        $banner="<div id="bannerHTML">123<!-- banner HTML goes here --></div>";

        // Append your banner HTML to the revslider's output
        return 
            is_callable( $callback ) 
            ? call_user_func( $callback, $atts, $content, $callback ) . $banner 
            : '';
    } );

}, PHP_INT_MAX );

Here we hook late into the after_setup_theme action and use call_user_func() to run the previous shortcode’s callback, similar how it’s done in do_shortcode_tag().

Leave a Reply

Your email address will not be published. Required fields are marked *