Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the thumbnail from a WP_Post object?

Tags:

php

wordpress

I'm trying to Loop over a bunch of pages under a certain taxonomy. The looping part works great, and I get all of the pages I need (nicely wrapped in WP_Post objects).

However, now I'm facing a different kind of problem. I want to include the page's thumbnail as set in the editor. I've tried any combination of get, the, thumbnail, featured, image, _, -, I could think of, to no avail.

The WP_Post object is rather new, and documentation is lacking.

Can anyone shed light on this mystery? My goal is to eventually show a bunch of <figure> elements, containing an image, a title, and a short description of each object.

like image 987
Madara's Ghost Avatar asked Dec 22 '12 22:12

Madara's Ghost


2 Answers

The following is just a proof of concept in form of shortcode. It dumps a code block with all posts that have a Featured Image.

Function reference: has_post_thumbnail, get_the_post_thumbnail

add_shortcode( 'all-post-thumbs', 'so_14007170_dump_post_thumbs' );

function so_14007170_dump_post_thumbs( $atts, $content ) 
{
    // Query
    $posts = get_posts( array(
        'post_type'    => 'post',
        'numberposts'  => -1,
        'post_status'  => 'publish'
    ) );

    // Build an array of post thumbnails
    $thumbs = array();
    foreach( $posts as $post)
    {
        if( has_post_thumbnail( $post->ID) )
            $thumbs[] = array( $post->post_title, htmlentities(get_the_post_thumbnail( $post->ID ) ) );
    }

    // Build output and return
    $echo = '<pre>'. print_r( $thumbs, true ) . '</pre>';
    return $echo;
}

Result in frontend:

var dump

Posts with featured image:

enter image description here

like image 87
brasofilo Avatar answered Sep 22 '22 05:09

brasofilo


Not sure what do you want but if you want to get all images of a certain page then you can use

$parent='your page id';
$args=array(
    'post_parent' => $parent,
    'post_type' => 'attachment',
    'post_mime_type' => 'image',
    'orderby' => 'menu_order',
    'order' => 'ASC',
    'numberposts' => -1 
);
$images = get_children($args);

You can paste this code in your loop and if you provide the appropriate page_id as parent then you'll get all images as an array in the $images and can run a loop.

Read more at Codex.

Update:

To get only the featured image you can use

echo get_the_post_thumbnail('page id here', 'thumbnail');

Read more at Codex.

like image 26
The Alpha Avatar answered Sep 21 '22 05:09

The Alpha