-
-
Save dleone81/ec3a4b3f502f35bd2929 to your computer and use it in GitHub Desktop.
/** | |
* 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 yes thats true :)
WC_Product_Factory::get_product_type($post->ID)
Is way more efficient than using wc_get_product
You are the best.
Since this was one of the top results in a Google search for me,
global $product;
$product_type = $product->get_type();
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"
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()
WC_Product_Factory::get_product_type($post->ID)
Is way more efficient than using wc_get_product