简体   繁体   中英

Wordpress: How to use get_the_post_thumbnail with $wpdb->get_results

I'm using get_results to get an array with data. Within this data has post ID. When I try retrieve the image with post ID I not retrieve the image. Any idea ?

This is my code.

First I add the next code in functions.php

/** 
 * Check to see if the function exists  
 * It is always a good practice to avoid any version conflict
 */

if(function_exists('add_theme_support'))
{
  /** Exists! So add the post-thumbnail */
  add_theme_support('post-thumbnails');

  /** Now Set some image sizes */

  /** #1 for our featured content slider */
  add_image_size( $name = 'itg_featured', $width = 500, $height = 300, $crop = true );

  /** #2 for post thumbnail */
  add_image_size( 'itg_post', 250, 250, true );

  /** #3 for widget thumbnail */
  add_image_size( 'itg_widget', 40, 40, true );

  add_image_size('projects_single',160,160, true);
  add_image_size('post',592,auto,true);
  add_image_size('post-mini',152,auto,true);
}

In my file that show the image I have the next code.

<?php   
  global $post,$wpdb;   
  $table = $wpdb->prefix.'posts';   
  $query = "SELECT * FROM $table WHERE post_type='startups' and post_status='publish' order by post_date desc limit 0,1; ";   
  $result = $wpdb->get_results($query);
?>

(This retrieve data perfectly).

Now, I do a foreach for retrieve data row to row.

foreach ($result as $key) {

 //retrieve post ID
 $idpost = $key->ID;

 //this line retrieve information to post_type
 $infostartup = get_post_meta($key->ID,array());

 //retrieve Image ID
 $imageid = get_post($infostartup['startup_photo'][0]);

 //Now I'm trying display image of post

 echo get_the_post_thumbnail($idpost);
 //this not display the image

 also I try using image ID but not display image.
 echo get_the_post_thumbnail($imageid);

}

Any idea?

If you have the image ID, you need to use wp_get_attachment_image_src( $imageid, 'itg_post' ) or whatever image size you want.

I also don't know why you're using a SQL query when you could do a WordPress query. Here's how you'd do it with WP_Query:

$args = array(
    'post_type' => 'startups',
    'posts_per_page' => -1
);
$loop = new WP_Query( $args );
if( $loop->have_posts() ): while( $loop->have_posts() ): $loop->the_post(); 
    global $post;
    echo get_the_post_thumbnail( $post->ID, 'image_size' );
endwhile; endif;
wp_reset_postdata();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM