Looking for a reason why get_post_meta()
doesn’t work with home.php
. From my reading I understand that it’s a template and not a post or page, per “Custom fields won’t display on my blog page”. The closest page I was able to find from searching was “get_post_meta fields don’t show up on posts page” but alas the answer doesn’t go into detail why. I have coded a custom meta box, it works, for the front_page.php
and all custom post types but not within home.php
. I am using a conditional is_home()
and it works but it seems get_the_ID()
doesn’t, the code:
if ( is_home() ) {
// variables
$check_meta = get_post_meta( get_the_ID(), 'checkbox', true );
$header_meta = get_post_meta( get_the_ID(), 'header', true );
$textarea_meta = get_post_meta( get_the_ID(), 'textarea', true );
// condition
if ( ( $check_meta == 'yes' ) && !empty( $textarea_meta ) && !empty( $header_meta ) ) {
// code
}
}
Why does get_the_ID()
appear to not work with get_post_meta()
in home.php
located in header.php
?
Edit:
Per the comments I thought I would edit this question to help someone else in the future. I am setting the the front page and the posts page in Settings -> Reading
. The below worked in my conditional for is_home()
:
$check_meta = get_post_meta( get_queried_object_id(), 'checkbox', true );
$header_meta = get_post_meta( get_queried_object_id(), 'header', true );
$textarea_meta = get_post_meta( get_queried_object_id(), 'textarea', true );
3 Answers
If your posts page is a static page selected under Settings > Reading > Front page displays, then get_queried_object_id()
will return the ID for that page which you can use to fetch meta data.
$check_meta = get_post_meta( get_queried_object_id(), 'checkbox', true );
$header_meta = get_post_meta( get_queried_object_id(), 'header', true );
$textarea_meta = get_post_meta( get_queried_object_id(), 'textarea', true );