Within this sql query I want to ‘limit’ which terms are returned based on a set of post ids. I am not sure if this is possible or where I would place a ‘post_in’ condition into the sql statements.

If I had this array of post ids :
$post_in = array(10,12,14,16,28,65);

$terms = get_terms('product_cat');
$term_ids  = wp_list_pluck( $terms, 'term_id' );

$query = array();
    $query['select'] = "SELECT COUNT( DISTINCT {$wpdb->posts}.ID ) as term_count, terms.term_id as term_count_id";
    $query['from']   = "FROM {$wpdb->posts}";
    $query['join']   = "
        INNER JOIN {$wpdb->term_relationships} AS term_relationships ON {$wpdb->posts}.ID = term_relationships.object_id
        INNER JOIN {$wpdb->term_taxonomy} AS term_taxonomy USING( term_taxonomy_id )
        INNER JOIN {$wpdb->terms} AS terms USING( term_id )
        " . $tax_query_sql['join'] . $meta_query_sql['join'];

    $query['where'] = "
        WHERE {$wpdb->posts}.post_type IN ( 'product' )
        AND {$wpdb->posts}.post_status = 'publish'
        " . $tax_query_sql['where'] . $meta_query_sql['where'] . "
        AND terms.term_id IN (" . implode( ',', array_map( 'absint', $term_ids ) ) . ")
    ";
    $query['group_by'] = "GROUP BY terms.term_id";
    $query             = implode( ' ', $query );
    $results           = $wpdb->get_results( $query );

    $term_counts = wp_list_pluck( $results, 'term_count', 'term_count_id' );

Read more here: Limit terms based on post ids using sql


Solution:

If you know the solution of this issue, please leave us a reply in Comment section, to update the question.


Wordpress related questions and answers: