When I do this:
function append_album_review_to_title( $title ) {
global $post;
if ( get_post_type( $post->ID ) == 'album_review' && in_the_loop() ){
return 'Album Review: ' . $title;
} else {
return $title;
}
}
add_filter('the_title', 'append_album_review_to_title');
The title is properly prepended-to, but only when viewing the actual page.
When I don't test for the loop by removing && in_the_loop()
, it properly prepends to the titles which are output by the plugin I use to auto-share my Published posts to Twitter. However, the problem is, if I don't test for the loop, the string is also prepended to every single nav menu item name.
What conditional statements can I use to test for nav menu items and skip them in the filter?
UPDATE 1
Thank you Ittikorn. I tried it but it doesn't work. I can see it's altering the <title>
but unfortunately the output with the sharing plugin is still the original title.
UPDATE 2
Much appreciation, and though both would get genuine upvotes from me for the detailed and insightful responses if I could upvote, unfortunately, none of the solutions provided by Sumit or Peter worked.
Sumit's solution worked in that it didn't needlessly break nav menu items by applying the filter to them, but it also did not apply the filter to the post-screen auto-social-sharing plugin, which is what I needed.
Peter's solution also didn't work and did the exact same thing is Sumit's. I tried playing around with it, but couldn't get it to target the post titles for in_the_loop AND for the social sharing plugin's use but not for nav menu items.
SOLUTION
Peter's and Sumit's answers did truly help me tremendously though and lead to me eventually finding the oslution.
Trying both answers I noticed that on the backend, the plugin would return warnings like "missing parameter 2" and "Notice: Trying to get property of non-object...', and so it occurred to me that unlike the front end (nav menu and the loop), in the backend, apparently an $id
is not being passed to the_title
and so I can use this as a conditional.
This code accomplishes what I need (ie, modify post title in the loop, do NOT modify nav menu items, and modify the_title
for use by a backend social sharing plugin):
function append_album_review_to_title( $title, $id = NULL ) {
if ($id) {
if ( get_post_type( $id ) == 'album_review' ){
return 'Album Review: ' . $title;
} else {
return $title;
}
} else {
return 'Album Review: ' . $title;
};
}
add_filter('the_title', 'append_album_review_to_title', 10, 2);
Let me know if you think I can improve this somehow or if this could potentially cause future problems if unattended. And thank you for all your help.