Ben Daggers
Ben Daggers

Reputation: 992

Insert Featured Image in CSS Background Property using PHP to support Media Queries

I have this codes to specifically resize the the images in every posts. I placed it in my Wordpress functions.php

//TYPEONE images for large screens

add_theme_support('TypeOne');
set_post_thumbnail_size( 1200, 600, true );
add_image_size( 'TypeOne', 1200, 600, true );



//TYPETWO images for medium screen

add_theme_support('TypeTwo');
set_post_thumbnail_size( 800, 350, true );
add_image_size( 'TypeTwo', 800, 350, true );



//TYPETHREE images for small screen

add_theme_support('TypeThree');
set_post_thumbnail_size( 420, 350, true );
add_image_size( 'TypeThree', 420, 350, true );

Now my issue is I want those images to be used as background images. I have the codes below:

<?php global $post; ?>
<?php
$src = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID) false, '' );
?>
<div style="background: url(<?php echo $src[0]; ?> ) !important;">text </div>

Unfortunately, this approach totally ignores the codes (found in my function.php file) that I set for the images sizes.

Here's what I'm trying to achieve:

**HTML**
<div class="image-container">

</div>


@media screen and (max-width: 1100px) {
    .image-container{
        background: url(INSERT THE URL OF THE **TYPEONE** IMAGE)
    }
}

@media screen and (max-width: 700px) {
    .image-container{
        background: url(INSERT THE URL OF THE **TYPETWO** IMAGE)
    }
}

@media screen and (max-width: 400px) {
    .image-container{
        background: url(INSERT THE URL OF THE **TYPETHREE** IMAGE)
    }
}

Well, my only problem is how do I call my preferred thumbail in css?

if i use this css code,

background:url('<?php the_post_thumbnail('TypeTwo'); ?>');

it's really not working..

would somebody share his/her knowledge here please? Thanks!

Upvotes: 0

Views: 156

Answers (1)

Nilambar Sharma
Nilambar Sharma

Reputation: 1740

Use following code to register image sizes. Put it in functions.php.

<?php
add_action( 'after_setup_theme', 'child_setup' );

function child_setup(){

  // Register image sizes
  add_image_size( 'TypeOne', 1200, 600, true );
  add_image_size( 'TypeTwo', 800, 350, true );
  add_image_size( 'TypeThree', 420, 350, true );

}

To find image details you can use following snippet.

<?php
global $post;
$post_thumbnail_id = get_post_thumbnail_id( $post->ID );
$type_one_image_details = wp_get_attachment_image_src( $post_thumbnail_id, 'TypeOne' );
$type_two_image_details = wp_get_attachment_image_src( $post_thumbnail_id, 'TypeTwo' );
$type_three_image_details = wp_get_attachment_image_src( $post_thumbnail_id, 'TypeThree' );
$type_one_image_url = $type_one_image_details[0];
$type_two_image_url = $type_two_image_details[0];
$type_three_image_url = $type_three_image_details[0];

You have now respective image URL. Use it in CSS as you require.

Upvotes: 1

Related Questions