Use get_queried_object_id()
to get the post ID of the current page/post when viewing a single page or post, regardless of whether or not you’re in the loop, or what the global $post
variable happens to be at that moment:
if ( is_page() || is_single() ) {
$post_id = get_queried_object_id();
$meta_alternate = get_post_meta( $post_id, 'extra_meta_alternate', true );
echo '<link rel="alternate" media="only screen and (max-width:400px)" href="' . $meta_alternate. '" />';
}
Note that I moved the get_queried_object_id()
and get_post_meta()
to inside the if statement. This is because if you’re not on a page or post, the queried object ID could be the ID of a category or tag. This makes sure you’re only getting the ID if you’re on a post or page.