woocommerce categories separation php code

31 Views Asked by At

Here's how we found the wordpress post category

<?php if (in_category('268')) { ?>
   All articles written here appear in category 268.  
<?php } ?>

How do we make the above code for woocommerce product category? I couldn't do it because I don't have much coding knowledge. Thank you everyone so far...

Tried with related wordpress and woocommerce codes, but no result

1

There are 1 best solutions below

2
Mahesh Thorat On

Try below code

$categories = get_terms( 'product_cat' ); // Get all WooCommerce product categories
foreach ( $categories as $category ) {
    $category_id = $category->term_id;
    $category_name = $category->name;
    $category_link = get_term_link( $category_id );
    $category_thumbnail = get_woocommerce_term_meta( $category_id, 'thumbnail_id', true );

    // Output the category section
    echo '<div class="category-section">';
    echo '<h2 class="category-title">' . $category_name . '</h2>';

    // Output the products in the current category
    $args = array(
        'post_type' => 'product',
        'posts_per_page' => -1,
        'tax_query' => array(
            array(
                'taxonomy' => 'product_cat',
                'field' => 'term_id',
                'terms' => $category_id,
                'operator' => 'IN'
            )
        )
    );
    $products = new WP_Query( $args );
    if ( $products->have_posts() ) {
        echo '<ul class="products">';
        while ( $products->have_posts() ) {
            $products->the_post();
            global $product;

            // Output the product details
            echo '<li>';
            echo '<a href="' . get_permalink() . '">';
            echo get_the_post_thumbnail( $product->get_id(), 'thumbnail' );
            echo '<h3>' . get_the_title() . '</h3>';
            echo '<span class="price">' . $product->get_price_html() . '</span>';
            echo '</a>';
            echo '</li>';
        }
        echo '</ul>';
        wp_reset_postdata();
    }

    echo '</div>';
}

This code will loop through all the WooCommerce product categories and output each category in its own section with a heading displaying the category name. It will then query all the products belonging to the current category and display them in an unordered list with their respective details.