Shortcode Not Working in Slider When Added To Post Title

I've coded a shortcode to add manually to specific post title fields so i can style part of a title

add_shortcode( 'green', 'green_shortcode' );
function green_shortcode( $atts, $content = 0 ) {

    $a = shortcode_atts( array(
        'class' = 'green',
    ), $atts );

    return 'span class=' . $a['class'] . '' . $content . '/span';
}

This works on the single post titles but doesn't parse the shortcode when pulling the title into a slider.

This is the messed up HTML output from the slider

h2a href=http://newlocal.local/this-is-a-featured-post-4/ title=This  is a Featured Post #4This span class=green is a Featured Post #4/span/a/h2

Here's a visual

I have added do_shortcode to the post title PHP but it doesn't fix the problem

do_shortcode( get_the_title() );

The slider uses a WP_Query

new WP_Query( $query_args );

printf( 'h2a href=%s title=%s%s/a/h2', get_permalink(), the_title_attribute( 'echo=0' ), get_the_title() );

Edit : This is whats added to functions.php to parse shortcodes in the post title. Works in single post titles but NOT when the post title is shown in a slider.

add_filter( 'the_title', 'do_shortcode' );

Topic get-the-title shortcode wp-query Wordpress

Category Web


do_shortcode() returns the content you pass it with the shortcodes, if any, filtered out (ie, processed).

So the code you've posted in your question won't work the way you want it to:

do_shortcode( get_the_title() );
printf( 
    '<h2><a href="%s" title="%s">%s</a></h2>',
    get_permalink(),
    the_title_attribute( 'echo=0' ),
    get_the_title() 
);

Instead you'll need to do something more like this:

$title = do_shortcode( get_the_title() );
printf(
    '<h2><a href="%s" title="%s">%s</a></h2>',
    get_permalink(),
    the_title_attribute( 'echo=0' ),
    $title
);

or

printf(
    '<h2><a href="%s" title="%s">%s</a></h2>',
    get_permalink(),
    the_title_attribute( 'echo=0' ),
    do_shortcode( get_the_title() )
);

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.