How to get thumbnail from WP_Post object?

I am trying to turn a bunch of pages under a specific taxonomy. The looping part works fine, and I get all the pages I need (beautifully wrapped in WP_Post objects).

However, now I am facing another problem. I want to include a page thumbnail, as indicated in the editor. I tried any combination of get , the , thumbnail , featured , image , _ , - that I could think of, but to no avail.

The WP_Post object is fairly new, and the documentation is lacking .

Can anyone shed light on this mystery? My goal is to ultimately show a group of <figure> elements containing an image, a caption, and a brief description of each object.

+4
source share
3 answers

The following is just a proof of concept in the form of a short code. It unloads a block of code with all messages that have Featured Image .

has_post_thumbnail 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 the interface:

var dump

Messages with Favorite Image:

enter image description here

+6
source

Not sure what you want, but if you want to get all the images of a specific page, 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 insert this code into your loop, and if you provide the corresponding page_id as parent , then you will get all the images as an array in $images and you can start the loop.

More details in Codex .

Update:

To get only your favorite image, you can use

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

More details in Codex .

+1
source
 if ( have_posts() ) : while ( have_posts() ) : the_post(); // stuff before thumbnail $thumbnail_args = array(); // insert whatever thumbnail args you want echo get_the_post_thumbnail(); // stuff after thumbnail endwhile; else: echo "<h2>Sorry, nothing to see here.</h2>"; endif 

Unfortunately, WP_Post methods are called very poorly. Most methods that interact with Post should have some kind of '_' and 'post' arrangement added to them.

0
source

All Articles