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:
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.
You can’t use
get_the_ID()
when you are not in the loop (eg. in nav menus). Fortunately, thethe_title
filter comes with the post ID in an extra argument.Change your code to this, to make it work in all places:
Why you not get ID from permalink? That’ s possible. You can check if post ID not exists to check by permalink parsing URL or direcly check GET if is permalink off. WP have a bunch of ways to get ID.
You also can use this function:
https://codex.wordpress.org/Function_Reference/url_to_postid