WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] TwentyEleven Mod - Using featured image in css (7 posts)

  1. superpotion
    Member
    Posted 3 years ago #

    I've created a TwentyEleven child theme. I want to use a featured image as a background in the page, inside <div id="primary">, using <style> tags. Inside header.php just before the closing </head> tag:

    wp_head();
    
     /* Get the featured image into the CSS
      * Check if this is a post or page,
      * and if it has a thumbnail.
    if ( is_singular() && has_post_thumbnail( $post->ID )) : ?>
    <style type="text/css">
    #primary {
       background: url("<?php
       echo get_post_meta($post->ID, 'thumb', true);
       ?>") no-repeat scroll right bottom #FFFFFF;
    }
    </style>
    <?php endif; ?>
    </head>

    The image does not display, but if I replace the get_post_meta() call with an actual url, it does. In other words, the get_post_meta() returns null or empty, and is confirmed with Firebug. It gets past the if() and the following is echoed into the html page source:

    <style>
    #primary {
       background: url("") no-repeat scroll right bottom #FFFFFF;
    }
    </style>

    What am I missing here?

    Denis

  2. esmi
    Forum Moderator
    Posted 3 years ago #

    Are you saving the featured image url in a custom field called "thumb".

  3. superpotion
    Member
    Posted 3 years ago #

    I'm using the featured image feature within TwentyEleven, I'll check the DB and see what it's called there...

  4. superpotion
    Member
    Posted 3 years ago #

    Thanks esmi, you got it - "thumb" doesn't exist in postmeta table. (I lifted the code directly out of the get_post_meta() example in the codex - I won't do that again!)

    Here's the working solution:

    <?php
    if ( is_singular() && has_post_thumbnail( $post->ID )) :
       $thumb_id = get_post_meta($post->ID, '_thumbnail_id', true);
       $thumb_url = wp_get_attachment_url($thumb_id); ?>
    <style type="text/css">
    #primary { background: url("<?php echo $thumb_url ;?>") no-repeat scroll right bottom #FFFFFF; }
    </style>
    <?php endif;
    ?>
  5. Akhilesh Shivaraj
    Member
    Posted 2 years ago #

    Hey superpotion,

    Do you add this code into the page.php file? Or the functions.php file? Sorry for the confusion.

    Thanks in advance,

    Blaze

  6. superpotion
    Member
    Posted 2 years ago #

    @Blaze - the code is in header.php of the child theme.

    Denis

  7. Akhilesh Shivaraj
    Member
    Posted 2 years ago #

    @Denis

    Thanks for clearing that up! :D

    Blaze

Topic Closed

This topic has been closed to new replies.

About this Topic