How to fetch all custom terms of posts having particular meta value in WordPress?

I an having around 6000 posts with different meta value to a particulate key ‘CC101_type’.
Now I want to fetch all terms of those posts having specific meta value.

    $args = array(
        'post_type'         => 'coupon',
        'posts_per_page'    => -1,
        'meta_query'        => array(
                'relation' => 'AND',
            array(
                'key'       => 'CC101_deactive',
                'value'     => "off",
            ),
            array(
                'Key'       => 'CC101_type',
                'value'     => 'Deals'
            )
        )
    );


    $query      = new WP_Query($args);
    $all_categories = array();
        foreach($query->posts as $post=>$p){
            $id = $p->ID;
            $terms = wp_get_post_terms( $id, 'coupon_category', array("fields" => "all") );
            foreach($terms as $k => $cat){
        $all_categories[$cat->term_id] = $cat->name;
        }
    }

I tried to do the above task by getting all posts first based on meta value and then get there terms.
But it returned nothing when I get all posts 'posts_per_page' => -1, on the other side when I limit it to 20 posts it starts working.

Read More

Is there any other way to do it ?

Related posts

Leave a Reply

1 comment

  1. You can use custom query like following:-

    global $wpdb;
    $args = "SELECT * FROM $wpdb->posts 
        INNER JOIN $wpdb->postmeta AS PM1 ON ($wpdb->posts.ID = PM1.post_id)
        INNER JOIN $wpdb->postmeta AS PM2 ON ($wpdb->posts.ID = PM2.post_id)
    WHERE $wpdb->posts.`post_type` = 'coupon' 
        AND (PM1.meta_key = 'CC101_deactive' AND PM1.meta_value='off')
        AND (PM2.meta_key = 'CC101_type' AND PM2.meta_value='Deals')
        AND $wpdb->posts.`post_status` = 'publish' 
    ORDER BY $wpdb->posts.`ID`";
    
    $loop = $wpdb->get_results( $args );
    foreach ($loop as $post)
    {
        //Here $post is single post object.
        //Do your action.
    }
    

    Change query according to your need.

    Hope it will help.