GingerGirl
GingerGirl

Reputation: 301

List posts with the same tag of current post in WordPress

I have a site with 500 000 posts and it's pretty slow.

In the bottom of every post on a WordPress site, I want to show only 3 random posts having the same tag of current post.

Note that every post has always 1 tag only (no more, no less).

I use the following code but the SELECT gets thousands of posts and it's extremely slow.

Using posts_per_page=3 it gets thousands of posts (with same tag) via query and after that, it shows 3 posts only but the MySQL load has been very high. Instead, the logic should be "find 3 posts only and then stop".

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

How would you change the above code to reduce the loading time of MySQL queries?

Upvotes: 2

Views: 1379

Answers (2)

Hebe
Hebe

Reputation: 810

enhancement would be

$post = get_post(); // if you don't have $post->ID already
$tag_ids = wp_get_post_tags( $post->ID, array( "fields" => "ids" ) ); // current tags
$args = array(
    "numberposts" => 3,
    "orderby" => "rand",
    "post__not_in" => array( $post->ID ), //exclude current
    "tax_query" => array(
        array(
            "taxonomy" => "post_tag",
            "field"    => "term_id",
            "terms"    => $tag_ids
        )
    )
);
$posts = get_posts( $args ); // getting posts

Upvotes: 0

WhereDidMyBrainGo
WhereDidMyBrainGo

Reputation: 311

If $id is the tag ID to match:

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

$query = new WP_Query($args);

Query selects 3 random posts with selected tag.

Is that better?

Upvotes: 1

Related Questions