0

I want to retrieve 5 posts using any given post ID with following criteria:

  1. If the post with the ID has any tags, then select the posts having same tags.
  2. If the post does not have any tags, then select the posts with same category.

I can do this with following condition statement. However the problem is in following situation:

Problem: If post has a tag, but there are less than 5 posts with that tag, in that case I want to first get the posts with the same tags and then remaining posts from the same category. I am unable to figure out how I can do this.

Here's my code:

$tags = wp_get_post_tags($post->ID);
if ($tags) {
    $tag_ids = array();
    foreach($tags as $single_tag) $tag_ids[] = $single_tag->term_id;

    $args=array(
        'tag__in' => $tag_ids,
        'post__not_in' => array($post->ID),
        'showposts'=> 5,
    );  

} else {
    $categories = get_the_category($post->ID);  
    if ($categories) {
        $category_ids = array();
        foreach($categories as $cat) $category_ids[] = $cat->term_id;

        $args = array(
            'category__in' => $category_ids,
            'post__not_in' => array($post->ID),
            'showposts'=> 5,
        );      
    }
}

1 Answer 1

0

Below is the solution for your problem If my understanding is right!

    if ($tags) {
    $tag_ids = array();
    foreach($tags as $single_tag) $tag_ids[] = $single_tag->term_id;

    $args=array(
        'tag__in' => $tag_ids,
        'post__not_in' => array($post->ID),
        'showposts'=> 5,
    ); 
    if( count($args) < 5 ) {
        $n = 5 - count($args);  //to get posts based on the category
        if ($categories) {
        $category_ids = array();
        foreach($categories as $cat) $category_ids[] = $cat->term_id;

        $args2 = array(     //this is the args array for category based posts
            'category__in' => $category_ids,
            'post__not_in' => array($post->ID),
            'showposts'=> $n,
            );      
    }
    }
    $args = array_merge( $args, $args2 );
} else {
    $categories = get_the_category($post->ID);  
    if ($categories) {
        $category_ids = array();
        foreach($categories as $cat) $category_ids[] = $cat->term_id;

        $args = array(
            'category__in' => $category_ids,
            'post__not_in' => array($post->ID),
            'showposts'=> 5,
        );      
    }
}

The logic I added to your code was not tested. So it might throw some errors!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.