Ask your WordPress questions! Pay money and get answers fast! Comodo Trusted Site Seal
Official PayPal Seal

Trying to echo URL for the_post_thumbnail - getting error WordPress

  • SOLVED

I am trying to retrieve the URL of a featured image so I can apply it as a background image.

I've set the featured image in functions.php as:


add_theme_support('post-thumbnails');


This is the code I am using in my page.php template



<?php if (has_post_thumbnail( $post->ID ) ): ?>

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

<div class="headerinner" style="background:url('<? echo $image; ?>)' 0 0 no-repeat;">

<?php endif; ?>



I have a featured image set for one of my pages, and when I visit the page, the image does not show up. When I look at the source code, this is what shows up:


<div class="headerinner" style="background:url('Array') 0 0 no-repeat;">



Why is the image coming up as "array" instead of the URL to the image being posted?

Answers (5)

2011-08-18

Kailey Lampert answers:

I believe
echo $image['0'];
should work

2011-08-18

Pippin Williamson answers:

You need to echo $image[0];

<div class="headerinner" style="background:url('<?php echo $image[0]; ?>)' 0 0 no-repeat;">

Also don't use php short tags. Never <? always <?php

2011-08-18

Gabriel Reguly answers:

Hi Dan,

Why not use this code?


<?php
if ( has_post_thumbnail() ) { // check if the post has a Post Thumbnail assigned to it.
the_post_thumbnail('thumbnail');
}
?>


Regards,
Gabriel


Gabriel Reguly comments:

Hi,

Pippin has a correct answer.

Regards,
Gabriel


Gabriel Reguly comments:

Hi,

So does Kailey ;-)

Regards,
Gabriel


Gabriel Reguly comments:

Hi again,

I see you forgot to close your div. Correct HTML and PHP follows:



<?php if (has_post_thumbnail( $post->ID ) ): ?>



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



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



<?php endif; ?>


Regards,
Gabriel


Dan | gteh comments:

thanks. I need just the URL, not the entire img src="" code that it generates.

The closing div is there, just a few lines down in the code that I did not include when pasting it here.

2011-08-18

Navjot Singh answers:

Instead of using $image use $image[0].

2011-08-18

Reland Pigte answers:

Because the return value of wp_get_attachment_image_src is array

(array) An array containing:

[0] => url
[1] => width
[2] => height

or false, if no image is available.


Your code should look like this:


<?php if (has_post_thumbnail( $post->ID ) ): ?>

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

<div class="headerinner" style="background:url('<?php echo $image[0]; ?>)' 0 0 no-repeat;">

<?php endif; ?>