0
votes

I am facing issue with a custom plugin, which will show related post by taxonomy from a particular category(mobile). If there are no post matching taxonomy, it should display other posts from that particular category. First I fetched all taxonomies and terms for the current post(single.php). Then I prepare a query argument using loop. The code works for the below cases,

a) I have not added any post tag(current post), then it's showing other posts from the same category(mobile),

b) If I have added a post tag, and there are other post matching the terms of that post tag.

But, it's don't work when I have added a post tag, and there are no post matching those terms. But, here I want, if there are no matching post by the terms, then just display other posts irrespective of terms. I can do this, using a new query when have_posts fails, but I am thinking if there are any other way to do this withing the same query args, please help

I am placing the code which I am trying to develop.

    $post_args = array();

    $taxonomies = get_post_taxonomies( $post );

    foreach ($taxonomies as $key => $taxonomy) {
        # code...
        if($taxonomy == 'category') continue;
        $terms =  wp_get_post_terms( get_the_ID(), $taxonomy );
        $term_array = array();

        if($terms){
            foreach ($terms as $key => $value) {
                array_push($term_array, $value->slug);
            }

            array_push($post_args,
                array(
                    'taxonomy' => $taxonomy,
                    'field'    => 'slug',
                    'terms'    => $term_array,
                    )
                );
        }
    }

    $tax_query = array();
    $tax_query['relation'] =  'OR';

    foreach ($post_args as $key => $value) {
        # code...
        array_push($tax_query, $value);
    }

    $args = array(
        'post_type' => 'post',
            // 'category_name' => 'mobiles',
        'post__not_in' =>  array($curr_post_id),
        'posts_per_page' => 10,
        'orderby' => 'relevance',
        'order' => 'ASC',
        'tax_query' => 
        array(
            'relation' => 'AND',
            array(
                'taxonomy' => 'category',
                'field'    => 'slug',
                'terms'    => 'mobiles',
                )
            ,
            array($tax_query)
            )
        );

    $the_query = new WP_Query( $args );
1

1 Answers

0
votes

After trying a lot, I just decided to use another post loop. Say, if there are no result from first loop, just select random post from the category. If there are few posts(Max 10 posts) from the first loop, then user another loop to select random posts excluding the post ids we get from first loop.