简体   繁体   English

WooCommerce 查看所有有变化的产品

[英]WooCommerce view all products with variations

I have a WooCommerce shop that holds variable products.我有一个 WooCommerce 商店,里面有各种不同的产品。

I want to create some sort of export (on a page) that shows me all products including variations in a table.我想创建某种导出(在页面上),向我显示所有产品,包括表格中的变体。

I am viewing all products and created a loop to get the variations but it only shows me one product variation.我正在查看所有产品并创建了一个循环来获取变体,但它只向我显示了一个产品变体。

<?php
/*
Template Name: Store Management
*/
if (!is_user_logged_in() || !current_user_can('manage_options')) wp_die('This page is private.');
// Get
$args = array(
    'post_type' => 'product',
    'numberposts' => -1,
);
$products = get_posts( $args );
echo '<pre>';
print_r($products);
echo '</pre>';

foreach($products as $product):

    $args = array(
        'post_parent' => $plan->ID,
        'post_type'   => 'product_variation',
        'numberposts' => -1,
    ); 

    $product = wc_get_product( $product->ID );

    $variations = $product->get_available_variations();
    echo '<pre>';
    print_r($variations);
    echo '</pre>';

endforeach;

?>

Can anyone tell me how to get all variations for all products?谁能告诉我如何获得所有产品的所有变体?

M. M。

Here is my code, to get all products and variations in WooCommerce v3+ :这是我的代码,用于获取 WooCommerce v3+ 中的所有产品和变体:

<?php
$args = [
    'status'    => 'publish',
    'orderby' => 'name',
    'order'   => 'ASC',
    'limit' => -1,
];
$all_products = wc_get_products($args);
foreach ($all_products as $key => $product) {
    echo $product->get_title();
    if ($product->get_type() == "variable") {
        foreach ($product->get_variation_attributes() as $variations) {
            foreach ($variations as $variation) {
                echo $product->get_title() . " - " . $variation;
            }
        }
    }
}

First of all don't override the product variable inside loop.首先不要覆盖循环内的产品变量。 Secondly you have to check weather product is simple or variable.其次,您必须检查天气产品是简单的还是可变的。 Because simple product will not have variants.因为简单的产品不会有变体。 So your code will be like this :所以你的代码会是这样的:

foreach($products as $product):
$product_s = wc_get_product( $product->ID );
if ($product_s->product_type == 'variable') {
    $args = array(
        'post_parent' => $plan->ID,
        'post_type'   => 'product_variation',
        'numberposts' => -1,
    );
    $variations = $product_s->get_available_variations();
    echo '<pre>';
    print_r($variations);
    echo '</pre>';
}
endforeach;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM