Choose different header images on different posts

Together with the WordPress Customizer a nice feature was introduced into WordPress: The header image. If a theme supports header images with add_theme_support() you can choose an image, which will be displayed in the header. I’ve read now an interesting question in a forum:

Can someone please tell me if it is possible to alter the header image in the theme Twenty Eleven (2.1) for every page?

I liked this question and thought to myself, there must be a nice filter function, you could use for this. So I started my search. The image gets output by get_header_image(), which can be found in wp-includes/theme.php. Of course, this function is using get_theme_mod(), which is located in the same file. get_theme_mod() expects the name of the mod as a parameter, in our case “header_image”.

Before get_theme_mod() outputs its result, the function filters it with the filter “theme_mod_{name}”. For the image, which is displayed in the header, the filter would be called “theme_mod_header_image”. Basically we are done here. We write a small function which filters our header image. In a first step the function checks with is_singular() if we are on a single page or post. If that’s the case, we check if the current page has the custom field “current-background”. If this field contains a valid URL, this URL will be returned. In every other case, our filter will return the standard header image, which the administrator defined in the Customizer:

The following two tabs change content below.
Seine erste Webseite hat David Remer 1998 in HTML verfasst. Wenig später war er fasziniert von DHTML und JavaScript. Heute konzentriert sich vor allem auf das Entwickeln von WordPress Themes und Plugins für Inpsyde. Außerdem hat er das Buch "WordPress für Entwickler" verfasst.

Latest posts by David Remer (see all)

This post is also available in: German