You need to change how you are doing whatever you are doing. But however you do it, you’ll need to make use of conditional statements.
I narrowed part of my issue down to $post not being available within my function, despite being called as a global.
I’ve been searching all morning but am not finding exactly why this is. I expected if I did global $post; then I could access $post->ID but for some reason it doesn’t pass at all.
Is there some limitation to passing $post within a function called by a hook?
Jonathan
Turns out $post only seems to be available to hooks running on the_content. I can now get the value I need from $post, but unfortunately the value is also always echoed to the screen. Despite me returning it, it’s being displayed and I’m not sure why.
How can I retrieve the $post->ID value I need from my the_content filter or action, without it printing to screen?
add_filter('the_content', 'return_post_id');
function return_post_id()
{
global $post;
$keyword = get_post_meta( $post->ID, '_wpg_def_keyword', true );
return $keyword;
}
This is always echoing $keyword when I only want it returned.
Thanks,
Jonathan
Been fighting with this all day & night and no matter what I try, the result of my function is always echoed and never returned to be used in the function that called the add_filter. What am I missing??
Jonathan
That’s how the filter works.
WordPress core is such that you only have access to the global $post variable inside ‘the loop’.
Use the ‘the_content’ filter if you want to change what post content gets sent to the browser. If you want to do something else, use a different hook.
I understand all that. And as you can see in the code snippet I posted, I can get what I need using the_content without an issue.
The problem is, it is then echoed TO THE SCREEN every time, and does NOT get returned.
So again I ask – how can I keep it from being echoed, and how can I get the value to return to the calling function so I can use it?
Jonathan
Turns out the answer was simply to use url_to_postid like this:
$keyword = get_post_meta( url_to_postid( “http://”.$_SERVER[‘SERVER_NAME’].$_SERVER[‘REQUEST_URI’] ), ‘_wpg_def_keyword’, true );
Works perfectly even from init.
Jonathan
Bookmark your topic and come back and read it 6 – 12 months time.