0

Is it possible to change the following code to display the "featured image" of a post/page using the style "background-image" instead of the image at the URL that is being pulled. I have messed around with the_post_thumbnail and get_the_post_thumbnail, etc.

Basically the theme is pulling a photo from somewhere else, but I want it to dynamically pull the featured image for whatever post/page that I am on. Thanks to all that can help.

if ( $item['image'] ) {
   $style = ' style="background-image: url(\''.esc_url( $item['image'] ).'\');" ';
}
  • Yes, it's possible, but you'll need to post some more code. Right now, the code you've posted simply sets the variable $style to a string, but nothing is actually attempting to display it. Generally speaking, setting inline CSS via php is a bad idea. I would recommend you place the img element onto your page and style it separately as opposed to trying to set it as the background-image via CSS. – Eckstein Nov 12 '17 at 5:41
0

Well, I have set the featured image or any other from post with this code:

Get the image

$image_id=get_post_thumbnail_id(get_the_ID());
$image_url = wp_get_attachment_image_src($image_id,'full');
$image_url=$image_url[0];

Set the image as background

<div id="full" class="full float-left" style="background-image:url(<?php get_image_url(); ?>);">

Your content here.

</div> 

Next, one example I made few years ago taking the image from random post, the image is set as background and cover class. See sample

.full {
    background-size: cover;
    width: 100%;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.