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.
Untested but should work
By using the get_posts wordpress function
Get All WooCommerce Product Details by Category
Get All WooCommerce Product IDs by Category
Tested and its working fine.
According to Woocommerce documentation WP_Query() or get_posts() should not be used:
WooCommerce Docs
Here’s my solution:
Note: category argument requires an array of slugs, not IDs.
(Tested and works with WordPress 5.9.3 & WooCommerce 6.4.1.)
Credit: @Christian Lescuyer
The above (accepted) answer didn’t work (more results than there should have been) for me (version 4.9.8)
The above works. I’m not really a WordPress person but I’d guess it’s a version thing…