Woocommerce - How to check product type in plugin Woocommerce - How to check product type in plugin wordpress wordpress

Woocommerce - How to check product type in plugin


The earliest you could expect to access any Woo classes would be the woocommerce_loaded hook which is now fired in the plugins_loaded hook. If you are saving on the woocommerce_process_product_meta hook then any callback there would have all the classes properly loaded. If you are testing outside of that callback (and not attached to any hook at all.... it would be possible for the classes to not all be properly loaded.

Additionally, if you are attempting to call get_the_ID() before the WP_Post object has been set up you won't get a correct value.

A more complete cuzd_general_fields_save routine would look like:

/** * Save meta box data. * * @param int     $post_id WP post id. */public function cuzd_general_fields_save( $post_id ) {    $_product = wc_get_product( $post_id );    if( $_product->is_type( 'simple' ) ) {    // do stuff for simple products    } else {    // do stuff for everything else    }    $_product->save();}

An update for Woo 3.0 would be to use the woocommerce_admin_process_product_object so you no longer need to instantiate the product object or run save() as Woo will handle that in core.

add_action( 'woocommerce_admin_process_product_object', array( $this, 'cuzd_general_fields_save') );

and the callback would then be modified to:

/** * Save meta box data. * * @param obj $_product WC_Product. */public function cuzd_general_fields_save( $_product ) {    if( $_product->is_type( 'simple' ) ) {    // do stuff for simple products    } else {    // do stuff for everything else    }}


Here's one way to check the product type without creating an instance of the product:

$product_type = get_the_terms( $product_id,'product_type')[0]->slug;


An easy way is to simply check the value of the posted select. You can then:

$product_type = $_POST['product-type'];if ( $product_type == 'simple' ) { // do what you want}