0

I am using the_title filter to add an HTML snippet under the title, as follows:

enter image description here

I only want the output to happen for the main title in the posts or page view.

That's why I added an early return to make sure that the filter only applies if is_singular() returns true:

if ( ! is_singular() ) { return; }

But there is an issue, since the title may be loaded in other places inside the single view template.

For example, the twentytwentyone theme displays the post or page edit link as follows:

edit_post_link(
sprintf(
     esc_html__( 'Edit %s', 'twentytwentyone' ),
     '<span class="screen-reader-text">' . get_the_title() . '</span>'
),
'<span class="edit-link">',
'</span>'
);

So I am having trouble with the HTML being output in places that I don't want.

How do you suggest to handle this situation (without touching the theme files) to make sure the snippet is only added under the main title area?

5
  • Which theme are you using ? Aug 14 '21 at 11:11
  • @GautamGolakiya This is a plugin oriented solution, so all WP Themes following current standards should work Aug 14 '21 at 13:07
  • 1
    The most reliable way would be to use custom hooks in the theme files, e.g. do_action( 'before_main_title' ); the_title(); do_action( 'after_main_title' );.. So you'd hook on the "after" action instead of the_title.
    – Sally CJ
    Aug 14 '21 at 14:13
  • @SallyCJ Thanks, yes, this seems to be the cleanest approach. In this case, though, I am required to not touch the theme, it should work on "all" themes via a Plugin. Aug 14 '21 at 14:18
  • 2
    Yes, I understand, but I don't think that's possible because as you already know it, the_title (i.e. the hook) might be fired in various places in the single template and remember there are also template parts.
    – Sally CJ
    Aug 14 '21 at 14:59

Your Answer

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

Browse other questions tagged or ask your own question.