I used the following code to get the list of product categories form WooCommerce in my WordPress website:
<?php
$taxonomy = 'product_cat';
$orderby = 'name';
$show_count = 0; // 1 for yes, 0 for no
$pad_counts = 0; // 1 for yes, 0 for no
$hierarchical = 0; // 1 for yes, 0 for no
$title = '';
$empty = 0;
$args = array(
'taxonomy' => $taxonomy,
'orderby' => $orderby,
'show_count' => $show_count,
'pad_counts' => $pad_counts,
'hierarchical' => $hierarchical,
'title_li' => $title,
'hide_empty' => $empty
);
?>
<?php $all_categories = get_categories( $args );
//print_r($all_categories);
foreach ($all_categories as $cat) {
//print_r($cat);
if($cat->category_parent == 0) {
$category_id = $cat->term_id;
?>
<?php
echo '<br /><a href="'. get_term_link($cat->slug, 'product_cat') .'">'. $cat->name .'</a>'; ?>
<?php
$args2 = array(
'taxonomy' => $taxonomy,
'child_of' => 0,
'parent' => $category_id,
'orderby' => $orderby,
'show_count' => $show_count,
'pad_counts' => $pad_counts,
'hierarchical' => $hierarchical,
'title_li' => $title,
'hide_empty' => $empty
);
$sub_cats = get_categories( $args2 );
if($sub_cats) {
foreach($sub_cats as $sub_category) {
echo $sub_category->name ;
}
} ?>
<?php }
}
?>
This works fine and returns the list of product categories. I have been trying now to get a list of products for a particular category.
Example: get all the products for with cat_id=34
.
I know products are stored as posts, and have been trying to get this done but can't seem to.
How do I get the list of products for a particular category?
This will list all product thumbnails and names along with their links to product page. change the category name and posts_per_page as per your requirement.
Do not use
WP_Query()
orget_posts()
. From the WooCommerce doc:You can retrieve the products you want like this:
WooCommerce documentation
This should grab all the products you want, I may have the post type wrong though I can't quite remember what woo-commerce uses for the post type. It will return an array of products