I'm in the process of developing a custom WordPress theme for one of our clients at BR. We're using a fairly standard design pattern where we set a custom image for the About page and then any subpages will use the same image. The difference for this project is that there are a couple pages that have their own special image so I wanted to be able to set a master image for a parent page but still give the child page a way to have custom images.
In the past I would have hard coded the images in custom page templates. But this is a bad idea for a number of reasons:
- A user can forget to select a page template, or can select an incorrect page template
- A user can't edit the image
- A user would have to contact me to create new page templates
I wanted something more flexible that involved less coding and gives the user more power but not so much they break the site. Haha, doesn't that sound like every technical problem?
I found a couple of scriptsΒ that had similar functionality but nothing that did what I wanted so I decided to write my own script. This script basically creates a list of ancestors and then loops through them looking for a featured image. If it finds a featured image it stops looping and then prints it to the screen. The script is pretty simple (just 15 lines of code) but it allows me to keep my page template files clean and the client can very easily set a featured image for whatever page they want. Win win.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
global $post; | |
if ( isset($post) ) { | |
//get the ancestors | |
$familyTree = get_ancestors($post->ID,'page'); | |
array_unshift( $familyTree, $post->ID ); //add the current page to the begining of the list | |
//loop through the family tree until you find a result or exhaust the array | |
$featuredImage = ''; | |
foreach ( $familyTree as $family_postid ) { | |
if ( has_post_thumbnail( $family_postid ) ) { | |
$featuredImage = get_the_post_thumbnail( $family_postid, 'full' ); | |
break; | |
} | |
} | |
// if the page has a featured image then show it | |
echo ( $featuredImage ? $featuredImage : "" ); | |
} |
Update:
Rachel Baker recommends checking to make sure that the post is set before checking other things. I've updated the original code.
Thank you, this is exactly what I needed.
You’re welcome. Nice site BTW. π
Thank you!
You’re welcome! π
Thanks for the time saver π
Added this as a function to functions.php so it can be reused throughout the theme I’m working on for a client.
Minor typo: semicolon is missing at the end of line 2.
Cheers!
Hey Laurens. Thanks for the correction! This is why I love posting this stuff. Makes me a better coder. Glad it worked for you. π