post_id always wrong in plugin

I am trying to make two plugins work together where one of them puts a tag around every title with a filter function. I want it to exclude posts of another plugin that have custom post_type (ai1ec_event). But I can’t get the post type if the id is wrong.

add_filter('the_title', 'mealingua_title_filter', 10);
function mealingua_title_filter($title) {
   $post_id = get_the_ID();
   #some stuff
   if (is_front_page() OR is_single() OR is_page()) {
        return '<span class="mealingua_title_container_' . $post_id . ' mealingua_title_container">' . $title . '</span>';
    } else {
        return $title;
    }
 }

But the post_id is always wrong in some places. One is the nav_menu at the top. The other is the plugin that I want to fix. There the id is always the one of the last post from the site. I tried the following to alternatives without success:

Read More
global $post;
$post_id= $post->ID;
global $wp_query;
$post_id = $wp_query->post->ID;

How can I work around this? What can I do? I am willing to mess with the code of either plugin but although I know PHP I have no experience with wordpress plugin coding. Thanks for any help.

Related posts

Leave a Reply

2 comments

  1. You can’t use get_the_ID() when you are not in the loop (eg. in nav menus). Fortunately, the the_title filter comes with the post ID in an extra argument.

    Change your code to this, to make it work in all places:

    function mealingua_title_filter($title, $post_id) {
    
      #some stuff
      if (is_front_page() OR is_single() OR is_page()) {
        return '<span class="mealingua_title_container_' . $post_id . ' mealingua_title_container">' . $title . '</span>';
      } else {
        return $title;
      }
    }
    
    add_filter('the_title', 'mealingua_title_filter', 10, 2);