I want to be able to echo the URL of the featured image of a post and after looking some on the web I found the following which works fine when I put it in a loop in my front page template.
<?php $thumbSmall = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'small' ); $urlSmall = $thumbSmall['0']; ?> <?php echo $urlSmall; ?>
However, want to use variable $urlSmall in other places than in the front page template, and this is where my limited coding skills let me down. I tried to just copy paste
wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'small' ); $urlSmall = $thumbSmall['0'];
into my functions.php but that did not work. I need these variables to be globally recognized. What do I do here? write some kind of function?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
You can turn your snippet into a function that returns the post thumbnail URL of a post:
function wpse81577_get_small_thumb_url( $post_id ) {
$thumbSmall = wp_get_attachment_image_src( get_post_thumbnail_id( $post_id ), 'small' );
return $thumbSmall['0'];
}
Usage, supplying the ID of a post:
<?php echo wpse81577_get_small_thumb_url( 59 ); ?>
Method 2
Pure PHP question, really.
global $urlSmall; $urlSmall = $thumbSmall['0'];
If you declare the variable with the global keyword when you initialize it it will be available thereafter. You can imprort it, so to speak, with…
global $urlSmall; var_dump($urlSmall);
You can do the same thing by assigning key/values directly to the $GLOBALS array.
$GLOBALS['urlSmall'] = $thumbSmall['0'];
That seems to be the most direct answer to the question:
I need these variables to be globally recognized. What do I do here?
There may be better ways to handle the data though.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0