程序创建的Woocommerce产品变体未在前端显示



首先插入父变量乘积:

$parent_product = array(
'post_title'   => 'Euro Washing Machine',
'post_content' => 'Some Description',
'post_type'    => 'product',
'post_status'  => 'publish',
'post_parent'  => '',
'meta_input'   => array(
'_rrp'        => 220,
'_sku'        =>'wedf4532d',
'_visibility' => 'visible'
)
);
$parent_product_id = wp_insert_post( $parent_product, true );
if ( ! $parent_product_id ) {
return 0;
}
wp_set_object_terms( $parent_product_id, 'variable', 'product_type' ); 
wp_set_object_terms( $parent_product_id, 'brand-new', 'pa_' . 'condition' );
$parent_data_attributes[ 'pa_' . 'condition' ] = array( 
'name'         => 'pa_' . 'condition',
'value'        => 'brand-new',
'is_visible'   => '1',
'is_variation' => '1',
'is_taxonomy'  => '1'
);
update_post_meta( $parent_product_id, '_product_attributes', $parent_data_attributes ); 

插入具有属性pa_condition 的产品变体


$variation_product = array( 
'post_title'  => 'Euro Washing Machine',
'post_name'   => 'product-' . $parent_product_id . '-variation',
'post_status' => 'publish',
'post_parent' => $parent_product_id,
'post_type'   => 'product_variation'
);
$variation_product_id = wp_insert_post( $variation_product ); 
update_post_meta( $variation_product_id, '_price', 221 );
update_post_meta( $variation_product_id, '_sale_price', 221 );
update_post_meta( $variation_product_id, '_regular_price', 221 );
update_post_meta( $variation_product_id, '_manage_stock', 'true' );
update_post_meta( $variation_product_id, '_stock', 1 );
$variation = new WC_Product_Variation($variation_product_id);
$variation->set_attributes( array(
'pa_condition' => 'brand-new'
) );
$variation->save();

以程序方式添加了在管理区域显示但不在前端显示的变体。如果我登录到管理员,然后点击更新产品,它就会出现在前面。

你能告诉我,我在这里缺了什么吗?

我遇到这个问题是因为在创建所有变体后,在可变产品上设置了产品类别。

$ret = wp_set_object_terms($variable_product_id, $term_id, 'product_cat');

如果我在创建所有变体之前在可变产品上设置类别,那么它就解决了问题。现在我可以在我的分类页面上看到所有的变化。

最新更新