Search code examples
wordpresswoocommercecategoriesproduct

Wordpress WooCommerce: is there a way to view all products that are not in a category?


There are certain products I only need to display in the USA. I have a category labelled ‘USA’ that contains them, however I need to place all of the products NOT in that category into a new one called ‘Rest of world’

Is there an easy way to do this?

I am trying to find a way to display the ~200 products (of my ~400 product store) in the USA without needing to go into each and every one and mark it or find the ID.

My plan is:

  1. find all products not in the USA category
  2. add those to a new ‘Rest of world’ category
  3. for the location of USA hide the category ‘Rest of World’
  4. otherwise show both categories

If there are better solutions out there I’m all ears!


Solution

  • People just putting -1 without any feedback nor reasons piss me off...

    Anw, the following should do the trick as long as your products are part of their respective categories. I've put a bunch of options just chose what suit you the best you can also take a look at this documentation to understand a bit about the wordpress query https://developer.wordpress.org/reference/classes/wp_query/

    It's just a generic loop where you specify the required post type (here product has you're using woocom) and required categories.

    If it's a custom taxonomy and not just a term inserted in the default product category then you might have to do some more tweaking but not a lot. Hope this will help you.

    <!-- Start loop here -->
    <?php
    /* For Choice 3 ONLY add the following:
    Warning: You need to use the category NAME
    $cat_id = get_cat_ID ( 'USA' ); */
    $query = new wp_query( array(
    'post_type'         => 'product',
    
    /* Choice 1 - Display product with category "USA" AND ALSO product with category "Rest of world"
    Using the separator ",".
    Warning: You need to use the category SLUG
    'category_name'     => 'usa,rest-of-the-world', */
    
    /* Choice 2 - Display product with category "USA" AND "Rest of world"
    Using the separator "+".
    Warning: You need to use the category SLUG
    'category_name'     => 'usa+rest-of-the-world', */
    
    /* Choice 3 - Display all products without category "USA"
    You could also use the category id
    'cat'     => '-' . $cat_id, */
    
    'post_status'       => 'publish',
    /* To display all products replace the post_per_page value by '-1'
    'posts_per_page'    => '-1', */
    'posts_per_page'    => '3',
    ) ); ?>
    <?php if ( $query->have_posts() ): while ( $query->have_posts() ): $query->the_post(); ?>
    <!-- Start template here -->
    <div><a aria-label="<?php the_title(); ?>" href="<?php the_permalink(); ?>"><?php the_title(); ?></a></div>
    <!-- End template here -->
    <?php endwhile; endif; ?>
    <!-- End loop here -->