首页 > 解决方案 > Wordpress 在显示每个类别的帖子时具有多个循环,我可以让它更快吗?

问题描述

所以我正在使用 wordpress 和自定义主题。在登录页面中,我想显示每个类别的帖子。

示例:假设我有猫、狗、驴三个类别。然后在我的登陆页面上,我会有类似的东西:

为此,我最终做了三个循环(也许更多的类别更多),所以基本上我最终写了这样的东西:

  <?php $posts = query_posts( array ( 'category_name' => 'cats', 'order' => 'ASC', 'posts_per_page' => 10 ) );?>
  <h1>my cats</h1>
  <?php
  foreach ($posts as $post) :
    if ($post):
   ?>
   <!-- displaying info not so important -->
   <div class="some_wrapper">
     <a href="<?php the_permalink();?>">
     <img <?php $turl = get_the_post_thumbnail_url(); echo ($turl !== false) ? 'src="' . $turl . '"' : 'src="https://i.picsum.photos/id/10/800/600.jpg"'; ?> alt=""/>
     <span><?php   echo get_the_title(); ?></span></a>
   </div>
  <?php endif;endforeach; ?>

  <?php $posts = query_posts( array ( 'category_name' => 'dogs', 'order' => 'ASC', 'posts_per_page' => 10 ) );?>
  <h1>my dogs</h1>
  <?php
  foreach ($posts as $post) :
    if ($post):
   ?>

   <!-- displaying info not so important -->
   <div class="some_wrapper">
     <a href="<?php the_permalink();?>">
     <img <?php $turl = get_the_post_thumbnail_url(); echo ($turl !== false) ? 'src="' . $turl . '"' : 'src="https://i.picsum.photos/id/10/800/600.jpg"'; ?> alt=""/>
     <span><?php   echo get_the_title(); ?></span></a>
   </div>
  <?php endif;endforeach; ?>

  <?php $posts = query_posts( array ( 'category_name' => 'donkeys', 'order' => 'ASC', 'posts_per_page' => 10 ) );?>
  <h1>my donkeys</h1>
  <?php
  foreach ($posts as $post) :
    if ($post):
   ?>
   <!-- displaying info not so important -->
   <div class="some_wrapper">
     <a href="<?php the_permalink();?>">
     <img <?php $turl = get_the_post_thumbnail_url(); echo ($turl !== false) ? 'src="' . $turl . '"' : 'src="https://i.picsum.photos/id/10/800/600.jpg"'; ?> alt=""/>
     <span><?php   echo get_the_title(); ?></span></a>
   </div>
  <?php endif;endforeach; ?>

一切正常,但是, 我可以让它更快吗,比如做一个循环而不是 3 个(或者更多,如果你有更多的类别)或者使用另一种循环方式?

标签: phpwordpressloopsoptimization

解决方案


推荐阅读