Get Ancestral Featured Image for WordPress

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.

Update:

Rachel Baker recommends checking to make sure that the post is set before checking other things. I've updated the original code.

6 thoughts on “Get Ancestral Featured Image for WordPress

  1. Thank you, this is exactly what I needed.

  2. Thank you!

  3. 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!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.