Skip to content

Instantly share code, notes, and snippets.

@dleone81
Last active June 27, 2024 18:42
Show Gist options
  • Save dleone81/ec3a4b3f502f35bd2929 to your computer and use it in GitHub Desktop.
Save dleone81/ec3a4b3f502f35bd2929 to your computer and use it in GitHub Desktop.
Woocommerce get product type
/**
* is_type can be simple, variable, grouped, external
* woocommerce_single_product_summary is hook!
* Put this into your functions.php (child-theme)
**/
add_action( 'woocommerce_single_product_summary', 'get_product_type', 5 );
function get_product_type() {
global $post;
if( function_exists('get_product') ){
$product = get_product( $post->ID );
if( $product->is_type( 'variable' ) ){
echo // do something with external products
}
}
}
@Tofandel
Copy link

WC_Product_Factory::get_product_type($post->ID)

Is way more efficient than using wc_get_product

@kshirodpatel
Copy link

@Tofandel yes thats true :)

@alisaleem252
Copy link

WC_Product_Factory::get_product_type($post->ID)

Is way more efficient than using wc_get_product

You are the best.

@luboslives
Copy link

Since this was one of the top results in a Google search for me,

global $product;
$product_type = $product->get_type();

@asumaran
Copy link

WC_Product_Factory::get_product_type($post->ID)

Is way more efficient than using wc_get_product

Not accurate. Better use wc_get_product if you are dealing with subscriptions.

wp> WC_Product_Factory::get_product_type(485)
=> string(9) "variation"
wp> wc_get_product(485)->get_type();
=> string(22) "subscription_variation"

@Tofandel
Copy link

Tofandel commented Jun 27, 2024

That's because those kind of plugins use a filter on woocommerce_product_type but the type you are getting is actually the one in the database, if you don't have any plugins that add product types with variations then you can stick to the first solution, but if you want something efficient for those

$id = 485;
$type = WC_Product_Factory::get_product_type($id);
$className = WC_Product_Factory::get_product_classname($id, $type); // This might already cover your needs
(new $className)->get_type(); // this is more efficient because it does not run another query to fetch the full product

wc_get_product runs around 4-5 queries while the above function only runs 1, of course, if you do need the product after that no matter what, then prefer wc_get_product()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment