Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 703
Mostafa Ghanbari Avatar asked Feb 14 '23 18:02

Mostafa Ghanbari


1 Answers

 $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

like image 168
Prince Singh Avatar answered Feb 24 '23 02:02

Prince Singh