Last active
October 29, 2024 15:35
-
-
Save AkramiPro/c8ddb83d253714730ac26d3a64e7941e to your computer and use it in GitHub Desktop.
WooCommerce get product default variation id (most efficient way)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Get default product variation | |
* | |
* note: this method check for exact match. | |
* | |
* @param mixed $product_id WC_Product|WP_Post|int|bool $product Product instance, post instance, numeric or false to use global $post. | |
* @param string $return Optional. The format to return the results in. Can be 'id' to return id of variation or 'object' for the product variation object. Default 'id'. | |
* | |
* @return int|WC_Product_Variation return 0 if not found. | |
*/ | |
function wc_get_default_variation( $product_id = false, $return = 'id' ) { | |
// do not use wc_get_product() to bypass some limits | |
$product = WC()->product_factory->get_product( $product_id ); | |
if ( empty( $product ) || ! $product instanceof WC_Product_Variable ) { | |
return 0; | |
} | |
if ( $product->has_child() ) { | |
$attributes = $product->get_default_attributes(); | |
if ( ! empty( $attributes ) ) { | |
$check_count = true; | |
$attributes_count = count( $attributes ); | |
// get in-stock (if enabled in wc options) and visible variations | |
$variations = $product->get_available_variations( 'objects' ); | |
foreach ( $variations as $variation ) { | |
$variation_attributes = $variation->get_attributes(); | |
// check count for first time | |
// if not match, it means that user do not set default value for some variation attrs | |
if ( $check_count && $attributes_count !== count( $variation_attributes ) ) { | |
break; | |
} | |
// no need to check count anymore | |
$check_count = false; | |
// remove 'any' attrs (empty values) | |
$variation_attributes = array_filter( $variation_attributes ); | |
// add 'any' attrs with default value | |
$variation_attributes = wp_parse_args( $variation_attributes, $attributes ); | |
// check is default | |
if ( $variation_attributes == $attributes ) { | |
if ( $return === 'id' ) { | |
return $variation->get_id(); | |
} | |
return $variation; | |
} | |
} | |
} | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment