0

Is there a safe way to get the post ID inside the_title()?

add_filter('the_title', "change_post_title");

function change_post_title($title){

}

I tried using global $post and get_the_ID(), but this won't work in some cases (e.g. on a single page where the_title() is being called inside the navigation to link to the next post. global $post and get_the_ID() will reference the single post instead of the post that is being linked to.)

With get_page_by_title() I'd have to spawn multiple queries to cover all post types.

Do I have to fall back to a custom query?

1

Some filters in Wordpress are just not user friendly and does not always quite do what one wants to.

the_title filter will apply changes to all instances of get_the_title() (which is used by the_title()). So widget titles, related posts titles and post link titles are all changed, which is a problem when you just need to target the main post on a single page for instance

I have recently bumped into this post by Josh Levinson on his blog while having the same issue. He suggested to make use of the loop_start action where you check whether or not you are in the main query, and if you are, apply your the_title filter. If the query is not the main query, simply remove the filter

I have made a few changes to the original code. Just a note, you need php 5.3+ as closures was only introduced in php 5.3

add_action('loop_start', function ($q)
{
    if($q->is_main_query()){
        add_filter( 'the_title', 'modified_post_title', 10, 2);
    }else{
        remove_filter('the_title','modified_post_title', 10, 2);
    }
});
function modified_post_title($title)
{
    global $post;
    ?><pre><?php var_dump($post->ID); ?></pre><?php 
}
  • thanks for the detailed answer, however, If I call e.g. next_post_link() on a content-single page the filter is also applied to the the_title() call from next_post_link() – Jay Feb 13 '15 at 16:41
  • I've tested this on twentyfourteen, and cannot replicate your problem – Pieter Goosen Feb 14 '15 at 3:28

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.