WordPress snippet: src thumbnail

WordPress permette di associare una thumbnail ad un post, pagina o post personalizzato. Se è facilissimo estrarre l’intera immagine da codice, grazie alle funzioni the_post_thumbnail() o get_the_post_thumbnail, che restituiscono il completo tag img, risulta meno intuitivo come ottenere il solo link:

1
2
3
4
// Se $post_id è l'id del post
$image_id = get_post_thumbnail_id($post_id);
$image = wp_get_attachment_image_src($image_id, 'full');
echo $image[0]

Da usare, ad esempio in:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
$args = array('category_name' => 'featured');
$posts = get_posts($args);
foreach($posts as $post) : ?>
  <a href="<?php echo get_post_permalink($post->ID) ?>">
  <img
    alt=""
    title="<?php echo get_the_title($post->ID) ?>"
    src="<?php
    $image_id = get_post_thumbnail_id($post->ID);
    $image = wp_get_attachment_image_src($image_id, 'full');
    echo $image[0] 
    ?>" />
  </a>
<?php endforeach;

La funzione wp_get_attachment_image_src() restituisce un array con url, width ed height.

Non ci sono commenti per questo Post

Lascia un commento

TAG XHTML PERMESSI: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> INSERIMENTO CODICE:
<pre></pre> // blocco generico
					<code></code> // blocco generico
					[cc_actionscript][/cc_actionscript] // Actionscript
					[cc_actionscript3][/cc_actionscript3] // Actionscript 3
					[cc_css][/cc_css] // CSS Style Sheet
					[cc_html][/cc_html] // HTML
					[cc_js][/cc_js] // Javascript
					[cc_objc][/cc_objc] // Objective-C
					[cc_php][/cc_objc] // PHP
					[cc_sql][/cc_sql] // SQL


Stop SOPA