I’m trying to get the home page of a WordPress theme I am building to change the background image on refresh based on 3 potential background images.
Each image is considered part of a larger “case study” that has a title, link, text, etc.
The case study fields are created through custom meta boxes on the home page. (I am using this to simplify the meta box creation process: https://github.com/jaredatch/Custom-Metaboxes-and-Fields-for-WordPress).
Long story short, the client wants 3 case studies on the home page to have corresponding background images. This is why I didn’t use the featured image functionality, as each background goes with specific meta data.
The problem is, I can’t figure out how to get the meta ID of the chosen background image and use that to set the background CSS.
Here is what I have so far:
/**
* Home Page Case Randomizer
*/
$GLOBALS['_home_case_number'] = rand(1, 3);
function home_case_number() {
if ( is_front_page() ) : // checks whether this is the home page
// get the meta image
$attachment_image = get_post_meta( get_the_ID(), '_home_case_background_' . $_home_case_number, true );
This is where I get confused. The above returns the appropriate image.jpg
file. How do I massage this to work with the below code?
The below code is adapted from http://s2webpress.com/responsive-featured-image-function-in-wordpress-themes/, and I’d like to use it to make sure I’m serving images responsively.
// store the image sizes in an array
$img_sizes = array( 'thumbnail', 'medium', 'large', 'full' );
// grab the URL for each image size and store in a variable
foreach ( $img_sizes as $img_size ) {
${ 'img_src_' . $img_size } = wp_get_attachment_image_src( $attachment_image, $img_size );
}
echo '<style type="text/css">
.featured-image {
width: 100%;
min-height:350px;
background-image: url(' . esc_url( $img_src_medium[0] ) . ');
}
@media screen and ( min-width: 400px ) {
.featured-image {
background-image: url(' . esc_url( $img_src_large[0] ) . ');
}
}
@media screen and ( min-width: 1000px ) {
.featured-image {
background-image: url(' . esc_url( $img_src_full[0] ) . ');
}
}
</style>';
endif;
};
add_action( 'wp_head', 'home_case_number' );
So do I go about this by getting the meta ID of the background image? Or the attachment ID? I don’t know how to do either at this point.
Any help is much appreciated!
I figured it out!
1) The CMB “plugin” saves the attachment ID as as another meta key by adding “_id” to the end of it, so I used that to get the attachment ID, and
2) I had variable scope issues. As soon as I called my global variable within my function, things started working. Here’s the final code:
Hopefully this will help someone else out there.