列出与WordPress中当前帖子具有相同标签的帖子

时间:2018-07-06 21:24:41

标签: mysql wordpress performance tags

我的网站上有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查询的加载时间?

1 个答案:

答案 0 :(得分:0)

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

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

$query = new WP_Query($args);

查询会选择3个带有选定标签的随机信息。

那好吗?

相关问题