2
votes

I usually write in javascript, but I'm currently trying to set up a Wordpress theme for a side project. I've found a few resources outlining how to use a set featured image as a div background image through inline styling, but they're a little old. I'm currently trying a basic method I found, and have tried updating it to match the current Wordpress Docs, but I'm new to PhP.

In my functions file I have:

add_theme_support( 'post-thumbnails' );

In my template file I have:

<?php $bgImg = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'large'); ?>

<section style="background: url('<?php echo $bgImg[0]; ?>') no-repeat;">

</section>

The section is rendering but the dev tools show "background: url((unknown))"

  1. Could someone point a poor javascript-er in the right direction with the php here?
  2. If someone is more familiar with wordpress, can they confirm for me that 'large' is a default image size, or do I need to register it?
2

2 Answers

1
votes

I use a similar approach:

$thumb_id = get_post_thumbnail_id();
$thumb_url_array = wp_get_attachment_image_src($thumb_id, 'thumbnail-size', true);
$thumb_url = $thumb_url_array[0];

<div class="image row" style="background: url('<? echo $thumb_url;  ?>'); ">content</div

Edit: Here is a list of image sizes by default. https://codex.wordpress.org/Post_Thumbnails#Thumbnail_Sizes

0
votes

Use the following code instead of yours.

<?php 
$featuredImg = get_the_post_thumbnail_url($post->ID, 'full');
if($featuredImg) {
    $bgImg = $featuredImg;
} else {
    $bgImg = get_template_directory_uri().'/images/default_bg.jpg';
}
?>
<section style="background: url('<?php echo $bgImg; ?>') no-repeat;">
</section>