sinanisler logo

Get Product Variations as Single Products, WooCommerce


function display_variation_products() {
    // WP_Query arguments to fetch product variations
    $args = array(
        'post_type' => 'product_variation',
        'posts_per_page' => -1, // Set to -1 to show all variations
    );

    // The Query
    $variations_query = new WP_Query($args);

    // The Loop
    if ($variations_query->have_posts()) {
        echo '<ul class="products">';
        while ($variations_query->have_posts()) {
            $variations_query->the_post();
            $variation = new WC_Product_Variation(get_the_ID());
            echo '<li class="product">';
            // Link to the parent product
            echo '<a href="' . get_permalink($variation->get_parent_id()) . '">' . get_the_title($variation->get_parent_id()) . '</a> - ';
            // Display the price of the variation
            echo $variation->get_price_html();
            echo '</li>';
        }
        echo '</ul>';
    } else {
        // No variations found
        echo 'No product variations found.';
    }

    // Restore original Post Data
    wp_reset_postdata();
}

// Use this function where you want to display the variations
display_variation_products();

Leave the first comment