0

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

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

Here's a visual

enter image description here

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( '<h2><a 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' );

1 Answer 1

1

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() )
);
3
  • No, that's what i tried and it doesn't work.
    – Dev
    Apr 7, 2021 at 6:42
  • Please edit your question to show the full code snippet that you're having trouble with. As it stands, it doesn't look like you're using do_shortcode() correctly.
    – Pat J
    Apr 7, 2021 at 14:03
  • the_title filter is used to allow sortcodes in titles
    – Dev
    Apr 8, 2021 at 16:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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