0
add_action ('the_title' , 'test'); 

function test($title) {

    $mycode = '<div>test</div>';

    echo $mycode . $title;

 }

I expected this functions.php code to add "test" before the post title. It does that. But it adds it also all over the place on the page. Not sure what's the logic, it seems it adds appends it to all menu items of the page.

Am I wrong on my usage of the_title? Or might there be theme interference here?

2
  • 2
    the_title is used for all page titles, post titles, and menu item labels (menu items are technically posts). If you only want it to apply to certain titles, you need to specify which in your code (just posts? just the current page? etc.). Also, the_title is a filter, not an action. So you should use add_filter() and return the result, not echo it. Commented Apr 24, 2020 at 0:37
  • thanks. And how would you constrain the_title to affect only title of (real) posts. If I filter by just posts, as you said menu item labels will be also considered which is unwanted. Commented Apr 24, 2020 at 10:04

1 Answer 1

1

the_title filter has two parameters passed to it, $title and $id. You could use the $id to check the current post type and then do stuff based on that.

add_action ('the_title' , 'test', 10, 2);
function test($title, $id) {
  return 'post' === get_post_type($id) ? '<div>test</div> ' . $title : $title;
}

The problem with this is that the filter is kind of not aware in which context it is called (naturally WP conditionals provide some context). So you might get unexpected results and end up with the custom title prefix/suffix showing up everywhere on a single view, e.g. the main menu, main title, related posts, sidebar, footer..., even if you just wanted to make the modification in only one part of your view. This of course depends on your setup, needs and use case.

1
  • Closest as it can get but indeed I get the code in unwanted places. Will have to edit templates anyway. Commented Apr 25, 2020 at 14:29

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.