I need a reliable way to get the post ID outside of the loop to use get_post_meta()
in the pre_get_posts
hook.
So far I found out that
get_queried_object_id()
works for all pages except the frontpage or blogpageget_option( 'page_on_front' )
gives the frontpage IDget_option( 'page_for_posts' )
gives the blogpage IDglobal $post; echo $post->ID;
seems not to work withpre_get_posts
(no idea why)
I tried to check the ID conditionally with different functions:
function show_id ( $wp_query ) {
if ( is_front_page() && is_home() ) {
// Default homepage
$id = get_option( 'page_on_front' );
} elseif ( is_front_page() ) {
// static homepage
$id = get_option( 'page_on_front' );
} elseif ( is_home() ) {
// blog page
$id = get_option( 'page_for_posts' );
} else {
//everything else
$id = get_queried_object_id();
}
// Debug
echo $id;
}
add_action ( 'pre_get_posts', 'show_id' );
It works for the blogpage and other pages but not for the static frontpage. I get these error notifications:
Notice: Trying to get property of non-object in ...\wp-includes\query.php on line 4520
Notice: Trying to get property of non-object in ...\wp-includes\query.php on line 4522
Notice: Trying to get property of non-object in ...\wp-includes\query.php on line 4524
Can you help?
Edit:
What I want to achive is to call get_post_meta()
at pre_get_posts
which will return an array of post IDs. Then I want to modify the main query with something like $query->set ('post__in', array($myIDs));
to get the posts based on the IDs in the metadata of the queried post.
NULL
to one of the normal conditionals. Have you tried$wp_query->is_front_page()
instead?$query->set ('post__in', array($myIDs));
to alter the main query.get_option()
and be done with the whole thing.save_post
hook or custom fields or...?