9

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);
   }
}
1
  • Enable the debug mode, and find out what's wrong with $post.
    – fuxia
    Dec 19, 2016 at 20:07

1 Answer 1

10

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 );
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.