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.

Read More

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.

Related posts

3 comments

  1. 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.

  2. 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.
    }
    
  3. 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

Comments are closed.