简体   繁体   中英

How To Make Featured Image/Post Thumbnail to be the background image of a DIV?

So I have this code:

<?php $background = wp_get_attachment_image_src( get_post_thumbnail_id( $page->ID ), 'full' ); ?>

<div  class="imgholder" style="background-image: url('<?php echo $background[0]; ?>');">

The first line (php) is to get and enable the featured image/Post Thumbnail to be the background image of my specified div container.

The second line is the div container with a css style of background that assigns the featured image/Post Thumbnail.

To summarize, the code works like it will make the featured image/Post Thumbnail ( in its default size ) as a background image.

The codes works like a charm, hands down to the person who coded that!

My situation, I want to modify this a that will fit to my needs.

I have a function below which is tasked to crop and resize the image.

add_theme_support('TypeOneImage');
set_post_thumbnail_size( 726, 525, true );
add_image_size( 'TypeTwo', 726, 525, true );

My problem is, how can I integrate the two codes into one.

What I'm trying to achieve here is to make the featured image/Post Thumbnail attachment 'TypeOneImage' to be the background of my div?

Why I don't like the first code above? It's because the first code generates the default or original size of the image. I need something smaller and cropped. I'm after the smaller size which i believe affects the site's speed.

Hope someone could help.

try this

<?php $background = wp_get_attachment_image_src( get_post_thumbnail_id( $page->ID ), 'TypeTwo' ); ?>

<div  class="imgholder" style="background-image: url('<?php echo $background[0]; ?>');">

I assume TypeTwo or 726 X 525is the size you want . If you looking for smaller size . either you change your function values to add_image_size( 'TypeTwo',640,560, true ); or add new one called

add_image_size( 'PostBg',640,560, true ); 

Last don't forget to Use Regenerate Thumbnails plugin to regenerate all your post Thumbnails

The later code, including the size attributes needs to be pasted in your theme's functions.php file, with the after_setup_theme hook.

For example-

function theme_setup(){
add_theme_support('TypeOneImage');
set_post_thumbnail_size( 726, 525, true );
add_image_size( 'TypeTwo', 726, 525, true );
}
add_action('after_setup_theme','theme_setup');

After this deactivate your theme, and reactivate it. Now, whenever you query an image of 'TypeTwo' size, you would get an image of 726x525 (due to add_image_size( 'TypeTwo', 726, 525, true ) ), and a query to the Featured Image would also return 726x525 (due to set_post_thumbnail_size( 726, 525, true ) ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM