I installed the Twenty Seventeen theme and a child theme. Now I want to add the following code to functions.php
to add meta data to the <head>
tag using the wp_head
action:
if ( is_single() ) echo get_post_meta($post->ID, "meta-head", true); ?>
I tried this, but it did not work:
add_action ('wp_head','hook_inHeader');
function hook_inHeader() {
if ( is_single() ) {
echo get_post_meta($post->ID, "meta-head", true);
}
}
The reason the code posted is not working is that $post
is not referencing the global $post
variable, which is the goal here.
Using get_the_ID()
is a good way of accessing the ID associated with the current post. That’s how I’d suggest doing it, but there are other ways too:
add_action ( 'wp_head', 'hook_inHeader' );
function hook_inHeader() {
if ( is_single() ) {
// Get the post id using the get_the_ID(); function:
echo get_post_meta( get_the_ID(), 'meta-head', true );
/* Or, globalize $post so that we're accessing the global $post variable: */
//global $post;
//echo get_post_meta( $post->ID, 'meta-head', true );
/* Or, access the global $post variable directly: */
// echo get_post_meta( $GLOBALS['post']->ID, 'meta-head', true );
}
}