Safe way to get the post ID in the_title()

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 
}

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)