0

I want to use a shortcode ([ex]...[/ex]) within the title of a post in order to style the text in a certain way (<h1>part of <span class="ex">title</span></h1>).

Thanks to add_filter( 'the_title', 'do_shortcode' );, it works perfectly with the_title.

But now, single_post_title which I use for <title> contains the shortcode as plain text <title>part of [ex]title[/ex]</title>. With add_filter( 'single_post_title', 'do_shortcode' );, the title becomes <title>part of <span class="ex">title</span></title>.

Is there a way to make shortcodes conditional: if it's resolved within the_title do this, within single_post_title do that?

3
  • You may be able to use current_filter() to check if you're in single_post_title and return the unformatted version.
    – Howdy_McGee
    Apr 6, 2023 at 16:28
  • there are a lot of places that use the title, and also don't support shortcodes or HTML tags, e.g. these shortcodes are going to be piped into twitter linkedin and facebook. Would it not make more sense to ask how to style titles in content and use shortcodes as an example instead of asking how to fix what you've already built? aka the X Y Problem fallacy? Shortcodes are not the only way to apply styling to portions of a title, there are better solutions
    – Tom J Nowell
    Apr 6, 2023 at 16:54
  • Thank you @Howdy_McGee, this is exactly what I've been looking for. Apr 7, 2023 at 9:17

1 Answer 1

0

Thank you, @Howdy_McGee! current_filter() is exactly what I've been looking for. Here is what I did:

function french_example( $atts , $content = null ) {
        $currentFilter = current_filter();
    if ($currentFilter == the_content) {
      return '<span class="ex" xml:lang="fr" lang="fr">' . do_shortcode($content) . '</span>';  
    }
    elseif ($currentFilter == the_title) {
      return '<span class="ex" xml:lang="fr" lang="fr">' . do_shortcode($content) . '</span>';  
    }
    else {
      return do_shortcode($content);
    }
}
add_shortcode( 'ex', 'french_example' );

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.