Enhance the header hero image code to use CMB2 to specify the image.
Last week I wrote about setting the hero image in Essence Pro to be the first product image. While simple to administer it is inflexible. Here I present code that allows you specify a different hero image.
When I replied to the Genesis WordPress Facebook group post I commented that I could add code to use CMB2 or ACF (Advanced Custom Fields) to allow specifying a hero image, instead of using the main product image. The hero image area dimensions are quite different from those for the product image so a product image is never going to look good there.
Using CMB2
I have used CMB2 before as ACF can slow down the site. Although it requires code to create meta boxes, this means that they cannot be accidentally changed or deleted by a curious client.
I had a quick browse of the CMB2 docs and found the ‘file‘ field type. I copied the example and tried it out. With a little bit of experimenting with the ‘context‘ and ‘priority‘ fields I was able to position the meta box directly under the ‘Product image‘ meta box.
Robust Rendering
While updating and testing the function to retrieve the uploaded hero image I was forced to add additional error checking for when hero image wasn’t set and for when there wasn’t a product image. It’s great that the function is now more robust.
Furthermore, the code will work even if CMB2 is not active, so it doesn’t need to check for it.
The Code
Update
A new user in the Genesis Facebook group successfully used the original code and wanted to set the header hero image product categories. He cleverly tagged me in the post. I had a few minutes free after dinner so I updated the code to support product categories.
I had to create a new CMB2 box because the data is stored in term meta for the product category (it’s in post meta for products). The code to retrieve the header hero image is different as I had to use get_term_meta(). The gist has been updated.
I like the possibility of this solution, but found when I used the code as is that pages or posts with favorite images were not using those in the header hero any longer, though it worked with products.
Also, strangely, layouts changed from content, sidebar to full width for everything
Any ideas?
@Terry: Are you using Essence Pro or a different theme? I probably didn’t check it on pages and posts with featured images.
The layout change is very bizarre as the code does not make any changes to the layout.
I tested my code on my local server. I found that is_int() was failing because $featured_image_id was a string e.g. “37”. I changed to use is_numeric() and this too failed even though the docs said it shouldn’t. I added 0 to the variable to cast it to a number. This worked. I have updated the code and added a comment about it.
I tested the code on Terry’s site and I didn’t see the layout change issues but there may be caching on the site. Fingers crossed that they were a glitch.