Woocommerce - How to check product type in plugin

Cloud_Ratha picture Cloud_Ratha · Nov 5, 2014 · Viewed 34.6k times · Source

I'm pretty new to wordpress/woocommerce and just started playing with creating a custom plugin.

So far I have I have added my custom woocommerce settings via the api.

I've run into a problem where I want to add a custom field on a single product in the product data tab.

I managed to display it using the following code:

add_action( 'woocommerce_product_options_general_product_data', array( $this, 'cuzd_general_fields' ) );
add_action( 'woocommerce_process_product_meta', array( $this, 'cuzd_general_fields_save') );

However now I need to check if the product type is simple or variation. I tried the following:

$product = new WC_Product( get_the_ID() );
        if( $product->is_type( 'simple' ) ) {
          //
}

However I get an error:

 Fatal error: Class 'WC_Product' not found in ....

I have a good feeling I'm trying to initiate the Product class before its been called. I most likely have the whole format of the class plugin wrong. Any reading material with good instruction / best practice would be appreciated.

Otherwise if the above is a simple fix please let me know.

Answer

helgatheviking picture helgatheviking · Jan 1, 2015

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
    }

}