Adam Bell
Adam Bell

Reputation: 1045

WordPress: Echo custom image size into background URL for Figure

I'm using a PHP echo statement to pull in an image into my background URL for a figure element. This is what I'm currently using:

echo '<figure class="fixedratio" style="background: url(' . wp_get_attachment_url( get_post_thumbnail_id( )). ');"></figure>';

This works, but it pulls the main image, no matter what size it is.

I created a custom image size in functions.php called custom-size. I'd like to use that size. I thought I could just add it inside the parenthesis for get_post_thumbnail_id but all it did was create errors.

So this does not work:

<?php if ( has_post_thumbnail() ) { ?>
    <?php echo '<figure class="fixedratio" style="background: url(' . wp_get_attachment_image_src( get_post_thumbnail_id(), 'custom-size')[0] . ');"></figure>'; ?>
        <?php } else { ?>
    <figure class="fixedratio" style="background: url('<?php bloginfo('template_directory'); ?>/img/photo-na.gif');"></figure>
<?php } ?>

Any ideas what would work to display my custom size?

Upvotes: 0

Views: 1103

Answers (1)

cabrerahector
cabrerahector

Reputation: 3948

There are a couple of issues here:

  1. If you check the documentation, you'll notice that the get_post_thumbnail_id() function accepts only one parameter (at the time of writing at least): the post ID. You're passing it the thumbnail size which is not right.

The wp_get_attachment_url() retrieves the URL of the given attachment ID. As the previous function, this one also accepts only one parameter (the attachment ID) so you can't use it to fetch a specific image size.

If you want to fetch a specific image size, use the wp_get_attachment_image_src() function instead:

$image_data = wp_get_attachment_image_src( get_post_thumbnail_id(), 'custom-size' );
echo '<figure class="fixedratio" style="background: url(' . $image_data[0] . ');"></figure>';
  1. When you add new image sizes in your functions.php file, these new image sizes aren't automatically generated by WordPress for all posts, only for new posts created from that moment on. You'll need to use the Regenerate Thumbnail plugin (or a similar option) to generate them for you. If you don't do this, WordPress will attempt to find an image of size 'custom-size' for a post and if it can't find it WordPress will return the closest one in size it finds (or the original one) instead.

Upvotes: 0

Related Questions