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?
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
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.
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; ?>