Home > front end >  Programmatically created Woocommerce Product Variation Not showing on Front-End
Programmatically created Woocommerce Product Variation Not showing on Front-End

Time:04-13

Inserting parent variable product first:

$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 ); 

Insert Product Variation with attribute 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();

Programmatically added variation showing on admin area but not showing on Front-End. If I logged in to admin and just hit update the product then it appears on the front.

Can you please tell me, What I am missing here?

CodePudding user response:

I got this problem due to setting up the product category on the variable product after creating all variations.

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

If I set the category on the variable product before creating all the variations then it solved the issue. Now I can see all variations on my category pages.

  • Related