2

I'm currently using this code to grab the featured image URL and insert it as a background image:

<?php $thumb = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'full' );?>
<div class='guideHeader' style='background-image: url(<?php echo $thumb['0']; ?>);'>

What I'd like to do is make this a conditional:

  1. If Parent Page > Insert Thumbnail URL.
  2. If child of Parent and has no featured image > insert parent thumbnail URL.
  3. If child of Parent and has featured image > Insert Thumbnail URL.
3
  • You really only need to do something different in case 2. You'll need has_post_thumbnail() and get_ancestors() (the page's immediate parent will be the zeroth element of the array that get_ancestors() returns).
    – Pat J
    Commented Jun 5, 2014 at 1:13
  • Sorry, can you show me what this would look like? I'm still fairly new to WP. I follow what you're saying but no idea how to translate that to the proper code.
    – Derek
    Commented Jun 5, 2014 at 1:37
  • Sure. I added an answer.
    – Pat J
    Commented Jun 5, 2014 at 1:50

1 Answer 1

4
<?php 
$id = $post->ID;
if( ! has_post_thumbnail( $id ) ) {
    // the current page has no feature image
    // so we'll see if a) it has a parent and b) the parent has a featured image
    $ancestors = get_ancestors( $post->ID, 'page' );
    $parent_id = $ancestors[0];
    if( has_post_thumbnail( $parent_id ) ) {
        // we'll use the parent's featured image
        $id = $parent_id;
    }

}
$thumb = wp_get_attachment_image_src( get_post_thumbnail_id($id), 'full' );
?>
<div class='guideHeader' style='background-image: url(<?php echo $thumb['0']; ?>);'>

The result is that, if the current page has a featured image set, that will be used. If it doesn't, but it does have a parent page, then we'll check to see if that parent has a featured image. If it does, we'll use that page's ID to get the featured image. If the parent page doesn't have a featured image, then we'll just use the current page's ID and let the chips fall where they may.

This is quick and dirty, and does no real error handling. (A glance at the Codex pages for get_post_thumbnail_id() and wp_get_attachment_image_src() indicates that they'll both return false if there's no featured image, which means that in the worst case your page won't have a background image.)

References

2
  • This works perfectly. I had the right idea in my head but I was WAY off with my implementation. The pages we use this one will always have a featured image at least on the parent level so that should be fine.
    – Derek
    Commented Jun 5, 2014 at 2:24
  • If you haven't yet -- bookmark the WordPress Codex (especially the Function Reference).
    – Pat J
    Commented Jun 5, 2014 at 2:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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