【问题标题】:Wordpress: How to use get_the_post_thumbnail with $wpdb->get_resultsWordpress:如何将 get_the_post_thumbnail 与 $wpdb->get_results 一起使用
【发布时间】:2012-11-30 13:09:54
【问题描述】:

我正在使用 get_results 来获取包含数据的数组。在此数据中具有帖子 ID。当我尝试使用帖子 ID 检索图像时,我没有检索图像。有什么想法吗?

这是我的代码。

首先我在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);
}

在显示图像的文件中,我有下一个代码。

<?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);
?>

(这完美检索数据)。

现在,我做一个 foreach 来逐行检索数据。

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);

}

有什么想法吗?

【问题讨论】:

    标签: php wordpress-theming wordpress


    【解决方案1】:

    如果您有图像 ID,则需要使用 wp_get_attachment_image_src( $imageid, 'itg_post' ) 或任何您想要的图像大小。

    我也不知道您为什么要使用 SQL 查询,而您可以执行 WordPress 查询。以下是使用 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();
    

    【讨论】:

    • 我同意这一点。如果您在 Wordpress 中使用 SQL 查询来获取与 Wordpress 相关的数据,那么很有可能您做错了。 Get The Post Thumbnail 是另一种可能的选择。
    • 如何进行 Wordpress 查询调用 post_type='startups' 并显示所有行?
    • 使用WP Query 是您最好的选择。
    • 非常感谢!,回复很有用!
    • 感谢您的帮助,我也会使用 WP_query。
    猜你喜欢
    • 1970-01-01
    • 2012-11-17
    • 1970-01-01
    • 1970-01-01
    • 2012-08-15
    • 2019-05-01
    • 2014-09-23
    • 2016-02-13
    • 2012-05-15
    相关资源
    最近更新 更多