ngulhane02
ngulhane02

Reputation: 53

How can I Insert Product type programmatically in woocommerce

I'm trying to create product with grouped & variable type but It's not working when I try

$result=wp_set_object_terms( $product_id, 'variable', 'product_type', false );

It shows me invalid taxonomy error and is not inserting the product_type into the database and so is not setting the product type.

I have to update or insert my product_type just as it does in admin from add product option.

Please help with this.thanks in advance.

Upvotes: 2

Views: 3663

Answers (3)

ngulhane02
ngulhane02

Reputation: 53

I got the solution that I have to register the taxonomy as

register_taxonomy('product_type', array( 'product_type' ));

in my function(user-defined) in function.php before calling

wp_set_object_terms( $product_id, 'grouped', 'product_type', false );

So it create product type as I pass as grouped/variable/external/simple.

Upvotes: 2

Nikhil
Nikhil

Reputation: 1450

I think you've written the code directly without using an action.

Try this,

function woo_set_type(){
    // Your code
    $result = wp_set_object_terms($product_id, 'simple','product_type');
}
add_action('init', 'woo_set_type');

I hope this helps

Upvotes: 0

Anil Kumar
Anil Kumar

Reputation: 44

Check given example:

// An array of IDs of categories we to add to this post.
$cat_ids = array( 6, 8 );

/*
 * If this was coming from the database or another source, we would need to make sure
 * these were integers:

$cat_ids = array_map( 'intval', $cat_ids );
$cat_ids = array_unique( $cat_ids );

 */

// Add these categories, note the last argument is true.
$term_taxonomy_ids = wp_set_object_terms( 42, $cat_ids, 'category', true );

if ( is_wp_error( $term_taxonomy_ids ) ) {
    // There was an error somewhere and the terms couldn't be set.
} else {
    // Success! These categories were added to the post.
}

Upvotes: 0

Related Questions