Himani
Himani

Reputation: 265

How to add a woocommerce product to the custom Product_type using php code?

A WooCommerce product is getting created easily but the product is getting added to the product_type:simple. I want to add the product to the "custom product_type:test"

static function createTicket($postId, $productDetails) {
$id = wp_insert_post(array(
    'post_type' => 'product',
    'post_title' => $productDetails['title'],
    'post_content' => $productDetails['description'],
    'post_status' => get_post_status($postId),
        'max_value' => 1,
));
update_post_meta($id, '_price', $productDetails['price']);
update_post_meta($id, '_regular_price', $productDetails['price']);
update_post_meta($id, '_wpws_testID', $postId);
update_post_meta($id, '_sold_individually', "yes");
wp_set_object_terms( $id, 'test', 'product_type' );
return $id;
}

I have added

wp_set_object_terms( $id, 'test', 'product_type' );

But nothing works

enter image description here

Upvotes: 0

Views: 843

Answers (1)

Ankur Bhadania
Ankur Bhadania

Reputation: 4148

Used product_type_selector hook

// add a product type
add_filter( 'product_type_selector', 'add_custom_product_type' );
function add_custom_product_type( $types ){
    $types[ 'test_custom_product_type' ] = __( 'test Product' );
    return $types;
}

Edit

Please check below links it help you more on this

Edit

Above code for older version of WooCommerce

Used this code for save product with custom product type. it working with WooCommerce 3.* Check this for more information https://gist.github.com/stirtingale/753ac6ddb076bd551c3261007c9c63a5

function register_simple_rental_product_type() {
    class WC_Product_Simple_Rental extends WC_Product {

        public function __construct( $product ) {
            $this->product_type = 'simple_rental';
            parent::__construct( $product );
        }
    }
}
add_action( 'init', 'register_simple_rental_product_type' );
function add_simple_rental_product( $types ){
    // Key should be exactly the same as in the class
    $types[ 'simple_rental' ] = __( 'Simple Rental' );
    return $types;
}
add_filter( 'product_type_selector', 'add_simple_rental_product' );

Upvotes: 1

Related Questions