【问题标题】:List posts with the same tag of current post in WordPress在 WordPress 中列出与当前帖子具有相同标签的帖子
【发布时间】:2018-12-15 11:59:22
【问题描述】:

我有一个有 500 000 个帖子的网站,而且速度很慢。

在 WordPress 网站上每个帖子的底部,我只想显示 3 个与当前帖子具有相同标签的随机帖子。

请注意,每个帖子始终只有 1 个标签(不多也不少)。

我使用以下代码,但SELECT 获得了数千个帖子,而且速度非常慢。

使用posts_per_page=3,它通过查询获得数千个帖子(具有相同标签),之后,它只显示3个帖子,但MySQL负载非常高。相反,逻辑应该是“只找到 3 个帖子然后停止”。

$posttags = get_the_tags();
foreach($posttags as $tag) {
$duot=$tag->slug; 
$duot2=$tag->name; 
}

$the_query = new WP_Query( 'tag='.$duot.'&posts_per_page=3' );
if ( $the_query->have_posts() ) {
echo '<h3>Other post with tag '.$duot2.'</h3><ul>';
while ( $the_query->have_posts() ) {
$the_query->the_post();
echo '<li >'.the_title().'</li>';
}
echo '</ul>';
} 

wp_reset_postdata();

您将如何更改上述代码以减少 MySQL 查询的加载时间?

【问题讨论】:

    标签: mysql wordpress performance tags


    【解决方案1】:

    如果$id是要匹配的标签ID:

    $args = array('numberposts' =&gt; 3, 'orderby' =&gt; 'rand', 'tag_id' =&gt; $id);

    $query = new WP_Query($args);

    查询选择 3 个带有选定标签的随机帖子。

    这样更好吗?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-21
      相关资源
      最近更新 更多