Woocommerce 从变体产品中获取父级的描述

Woocommerce get parent's description from variation product

我正在尝试从一系列变体中获取父产品的描述。

我这样试过

$args = array(
            'numberposts'   => -1,
            'post_type'     => 'product_variation',
            'suppress_filters' => false,
            'orderby'       => 'title',
            'order'         => 'DESC'       );
$products = get_posts( $args ); 
foreach ( $products as $productId ) {
                $product = wc_get_product( $productId );    
                $parent = $product->get_parent_data();
    ....

其中产品是我的变体。但是在父数据中我没有描述。 关于如何获取描述的任何建议?

您可以使用 get_parent_id 获取父产品 ID。试试下面的代码。

$args = array(
    'numberposts'      => -1,
    'post_type'        => 'product_variation',
    'suppress_filters' => false,
    'orderby'          => 'title',
    'order'            => 'DESC'       
);

$products = get_posts( $args ); 

$productsIds = array(); // store product id for avoid duplication.

foreach ( $products as $variation_id ) {
    
    $variation = wc_get_product($variation_id);
    $product   = wc_get_product( $variation->get_parent_id() );

    if( !in_array( $product->get_id(), $productsIds ) && $product ){
        $productsIds[]             = $product->get_id();
        $product_details           = $product->get_data();
        $product_full_description  = $product_details['description'];
        $product_short_description = $product_details['short_description'];
    }

}