kesernio
kesernio

Reputation: 115

Set featured image as background in div

After scouring the internet I found a way to set a Wordpress featured image as a background image in a div. The problem now is that I'm only ably set the styles for the background image of that div in-line. I want to be able to set the styles in my css file, but am unsure how.

Here's my code:

<?php
$src = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), array( 5600,1000 ), false, '' );
?>
<div style="background: url(<?php echo $src[0]; ?> ) no-repeat center; width:100%; height: 300px; background-size:cover;"></div>

Any help would be appreciated.

Upvotes: 1

Views: 4633

Answers (2)

Shebin Xavier
Shebin Xavier

Reputation: 63

Use this code with inline css echo wp_get_attachment_url( get_post_thumbnail_id() );

Upvotes: 0

Alexander O&#39;Mara
Alexander O&#39;Mara

Reputation: 60527

CSS files are static, but WordPress's featured images and attachments are dynamic. The best way to handle this would be set the background-image inline, and set the rest of the background properties in the CSS file.

PHP

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

HTML

.featured-image {
    background: no-repeat center;
    width: 100%;
    height: 300px;
    background-size: cover;
}

Upvotes: 1

Related Questions