wordpresswoocommerce

Get Products by Category id


i am writing a pricing table plugin for woocommerce. the user inserts the shortcode with an id of woocommerce products category and after updating the page the user can see a table with a list of product's names and prices.
how can i get a list of products with the id of their category?!
in the code below $pid is what the user type in shortcode, 'object_id' is the id of the every product in wp_posts table.

<?php
    $products = $wpdb->get_results("SELECT object_id FROM {$wpdb->term_relationships}
                                      WHERE term_taxonomy_id = " . $pid);
    if(!empty($products))
    {
        foreach($products as $product)
        {
            //the code
        }
    }
?>  

Thanks in advance.


Solution

  •  $args = array(
        'post_status' => 'publish',
        'tax_query' => array(
           array(
             'taxonomy' => 'product_cat',
             'field'    => 'term_id',
             'terms'     =>  '[ category id here ]', // When you have more term_id's seperate them by komma.
             'operator'  => 'IN'
             )
           )
        );
        $the_query = wp_query($args);
    

    Untested but should work