I am trying to insert a WooCommerce element to display "products" (courses) from a specific category into a page.
I had also to hide these products for this specific category and it worked as expected. I just added a a filter inside functions.php and was it:
/*
* Exclude "packages" category from "Archive Products" on page 811
* Ref. URL: https://docs.woocommerce.com/document/exclude-a-category-from-the-shop-page/
*/
function exclude_category_archive_products( $q ) {
$tax_query = (array) $q->get( 'tax_query' );
$tax_query[] = array(
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => array( 'packages' ),
'operator' => 'NOT IN'
);
$q->set( 'tax_query', $tax_query );
}
if( $current_post_id != "811" ) {
add_filter( 'woocommerce_product_query', 'exclude_category_archive_products' );
}
/* END Exclude "packages" category from "Archive Products" on page 811 */
I have searched for ways to to achieve the opposite and I did not find anything "from this year or close". I’ve tried to use the "IN" or "=" operator but it didn’t work (it displays everything):
/*
* Display "packages" category only
*/
function show_only_category_in_page( $q ) {
var_dump("It reaches the function");
$tax_query = (array) $q->get( 'tax_query' );
$tax_query[] = array(
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => array( 'packages' ),
'operator' => '='
);
$q->set( 'tax_query', $tax_query );
}
if( $current_post_id == "811" ) {
var_dump("It reaches the page");
add_filter( 'woocommerce_product_query', 'show_only_category_in_page' );
}
/* END Display "packages" category only */
The previous code writes the string(23) "It gets reachs the page"
only. What am I doing wrong?
2
Answers
You should try this for that you can get products from a specific category
Solution 1:
Where 1,2,3 your category id.
Solution 2
Create a custom page and show specific categories of products:
Steps:
Get products of specific product category (by category slug or id):
I would like to update Rajeev Singh’s solution, especially the solution for displaying products of specific product categories.
Problem:
According to Woocommerce documentation WP_Query() or get_posts() should not be used:
WooCommerce Docs
Solution 1 – get products by category slug
Note: category argument requires an array of slugs, not IDs.
If you would like use the id of the product category on the specific category archive page check solution 2. How to get the ID of the current category from the category archive page template is not part of this solution.
Solution 2 – get products by category id:
Solution – display products
(Tested and works with WordPress 5.9.3 & WooCommerce 6.4.1.)
Credit: @Christian Lescuyer