doudou_3636 2013-11-05 16:23
浏览 42
已采纳

获取Wordpress帖子,以便get_post_thumbnail_id之类的东西不会进行数据库调用

Is there a way to fetch Wordpress posts so that meta calls don't actually do database calls?

For example, I currently have:

$args = array(
  'posts_per_page' => 1000,
  'post_type' => 'portfoliosample'
  );
$query = new WP_Query($args);
while($query->have_posts()):
  $query->the_post();
  $style = '';
  if(has_post_thumbnail($post->ID)){
    $image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'single-post-thumbnail' );
    $largeurl = $image[0];
    $style = ' style="background-image:url('.$largeurl.');"';
  }

?>
    <li id="post-<?php the_ID(); ?>" <?php post_class('half'); ?>>
      <a href="<?php the_permalink()?>"<?php echo $style?> ng-click="lightbox('portfolio','<?php the_permalink()?>')">
        <h3 class="entry-title caps"><?php echo strtoupper(the_title('', '', false)); ?></h3>
        </a>
    </li>
<?php
endwhile;

Things like the_title() do not make database calls because post has that information. However, $post seemingly does not have the post's thumbnail ID or that thumbnail's image source.
If I do a custom query like this:

global $wpdb;
$query = "
    SELECT posts.*
    FROM $wpdb->posts posts
    WHERE posts.post_type = 'portfoliosample'
    AND posts.post_status = 'publish'
    ORDER BY posts.menu_order ASC
";
$pageposts = $wpdb->get_results($query, OBJECT);
if($pageposts)
{
    global $post;
    foreach($pageposts as $post)
    {
        setup_postdata($post);
        $style = '';
        if(has_post_thumbnail($post->ID)){
            $image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'single-post-thumbnail' );
            $largeurl = $image[0];
            $style = ' style="background-image:url('.$largeurl.');"';
        }
        ?>
        <li id="post-<?php the_ID(); ?>" <?php post_class('half'); ?>>
            <a href="<?php the_permalink()?>"<?php echo $style?> ng-click="lightbox('portfolio','<?php the_permalink()?>')">
                <h3 class="entry-title caps"><?php echo strtoupper(the_title('', '', false)); ?></h3>
            </a>
        </li><!-- #post-## -->
        <?php
    }
}

Can I fetch the meta at the same time but still allow functions like get_post_thumbnail()? I was hoping that setup_postdata() would have a way to handle that.

  • 写回答

2条回答 默认 最新

  • duanjue6575 2013-11-17 19:15
    关注

    There isn't a way to do what I want. You either have to do everything those functions do manually, or allow them to make database calls.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化