Dynamically setting an image as the header image on a WordPress theme
I'm working on an interesting project using a Raspberry Pi Zero W computer with the Pi Camera module. Basically the idea is to take scheduled periodic photos via the Pi Zero and camera and then upload them to a WordPress site and then set the latest photo as the Header Image.
There was one thing that took me a little while to figure out and that was how to set the desired image as the header image in WordPress, I struggled to find anything whilst Googling so I thought I'd quickly write up a post about it.
Here's a quick explanation of how the project works. The Pi Zero runs a shell script via a cron job and captures an image, this script triggers a PHP file which uploads the image via a CURL call to the WordPress site via the Media endpoint of the WordPress Rest API. Once the image is uploaded a custom WP API endpoint is called which then sets this image as the header image.
It's this latter part that took a bit of time to figure out but it's actually quite simple to do, the header image is set as part of the theme mods settings, specifically a theme mod called "header_image", so all that's needed is a call to the "set_theme_mod" function like so:
Basically pass the full url of the uploaded image you want to be the header image. For my script I got the full url of the image using the "wp_upload_dir()" function so my script looks like this:
$uploads = wp_upload_dir();
set_theme_mod( 'header_image', $uploads['url'] . '/'. $imagefilenamehere );
Anyway, hopefully that might be of help to someone else! Watch the line breaks in the above code don't cause any problems.
Tags: raspberry pi,pi,pi zero,wordpress,wp rest api,rest api,raspbian
Originally published on 2017-04-18 12:24:35 by Rick Curran
Last edited on 2017-04-18 12:30:04 by Rick Curran
There are currently no Visitor Comments for this post.