Patrick's Programming Blog

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:

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.

Exit mobile version