Woocommerce get product ID’s from Category

So on my template for taxonomy-product_tag.php, I want to get all product id’s from the Category.

Here is how I currently do it

Read More
<?php
            $post_ids = array();
            $args = array( 'post_type' => 'product', 'posts_per_page' => 1, 'product_cat' => 'dog-collars', 'orderby' => 'rand' );
            $loop = new WP_Query( $args );
            if ( $loop->have_posts() ) {
            while ( $loop->have_posts() ) : $loop->the_post();

                $post_ids[] = get_the_ID();


            endwhile;
            } else {
            echo __( 'No products found' );
            }

            wp_reset_query();
            print_r($post_ids); 
        ?>

I can loop through the product_cat, pull id’s into an array and then further down the page I use foreach and the WC product factory to manipulate data how I want it shown for users.

My problem is I need the loop to be Dynamic based on categories, and I can’t understand how to do this.

I did think I can just grab the category name from the url

<?php $actual_link = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"; ?>

Grab it and the parse to just get the last , i.e category name, and then print into loop

But this seems like it would be a really poor way of doing it.

What I want is in the args

$args = array( 'post_type' => 'product', 'posts_per_page' => 1, 'product_cat' => 'DYNAMICHERE', 'orderby' => 'rand' );

I want to be able to populate product_cat dynamically based on the category I am on

Any help or advise / pointing me in the right direction would be appreciated

Related posts

Leave a Reply

1 comment