How to use get_post_custom function on the blog page?

First, I have a static page for homepage and for blog page too. I created a custom box for pages to setup unique background image for the pages. My idea is working on all page templates, but on blog page something wrong.

header.php is same on all page

<head>
{...}
<?php $values = get_post_custom( $post->ID );  ?>
<style type="text/css">
    body { background-image:url("<?php echo $values['background_image_meta'][0]; ?>"); }
</style>
{...}
</head>

Related posts

Leave a Reply

2 comments

  1. The basic problem is that there is no variable $post in your header.php. That variable might exist in the global scope, but your code operates in a function scope of load_template() which was called by get_header().

    So you have four options:

    1. Import the global variable into your function with the global keyword.
      global $post;

      // make sure everything is set up as a post object
      $post   = get_post( $post );
      $values = get_post_custom( $post->ID );
      
    2. Use get_queried_object_id() to get the ID, similar to hepii110’s suggestion.

      $values = get_post_custom( get_queried_object_id() );
      
    3. Use get_the_ID(). This does almost the same as version 1.

      $values = get_post_custom( get_the_ID() );
      
    4. Call get_post_custom() without the post ID. It will try to find the correct ID automagically.

      $values = get_post_custom();