I need to set the background of a div to the image of the post via PHP. I'm using wordpress and have the following code:
<?php if (has_post_thumbnail()); ?>
<img src="<?php the_post_thumbnail_url('largest'); ?>" class="img-fluid">
I want to use this code to set the background of some divs that are on the homepage for design purposes.
I have tried setting it using a styles.php file but I'm either coding it completely wrong or it doesn't work, the code I tried is as follows:
<?php
header("Content-type: text/css; charset: UTF-8");
?>
.slider-card {
background-image: url(<?php if (has_post_thumbnail()); ?>
<img src="<?php the_post_thumbnail_url('largest'); ?>" class="img-fluid">
)
};
If there is any way to make it so that the background image for my .slider-card divs can be automatically filled using the user-uploaded image it would be great if someone could teach me! All help appreciated.
EDIT:
This was the code when I checked it in the browser.
url(<br />
<b>Fatal error</b>: Uncaught Error: Call to undefined function has_post_thumbnail() in C:xampphtdocsMedia Site WPwp-contentthemesMediaThemestyle.php:6 Stack trace: #0 {main} thrown in <b>C:xampphtdocsMedia Site WPwp-contentthemesMediaThemestyle.php</b> on line <b>6</b><br />
I think your html and php is wrong.Try this:
<?php
header("Content-type: text/css; charset: UTF-8");
?>
.slider-card {
background-image: url(<?php if (get_the_post_thumbnail() != null){get_the_post_thumbnail();} ?>
}
<img src="<?php the_post_thumbnail_url('largest'); ?>" class="img-fluid">
1st you should know is that has_post_thumbnail() works only inside of the loop, so from the code you shared there is no way the function to work like this. Outside the loop you SHOULD pass the current post id and then use get_the_post_thumbnail_url() instead, so you pass 2 parameters there - id and size:
$page_id = get_queried_object_id();
<?php if (has_post_thumbnail($page_id)): ?>
<img src="<?php get_the_post_thumbnail_url($page_id, 'largest'); ?>" class="img-fluid">
<?php endif; ?>