问题
I am using Show stock status next to each attribute value in WooCommerce variable products answer code to display the variation stock status on single product attribute dropdown for variable product pages.
This works fine, but take too much time to load a product.
How could I optimize the code to make it load faster?
回答1:
Use the following instead, that will be a bit lighter (so variable products should load quickly):
add_filter( 'woocommerce_variation_option_name', 'customizing_variations_terms_name' );
function customizing_variations_terms_name( $term_name ){
global $product;
if( is_admin() ) return $term_name; // Only on frontend single products
// Iterating through each visible product variation Ids
foreach( $product->get_visible_children() as $variation_id ){
$variation = new WC_Product_Variation( $variation_id );
$stock_status = $variation->get_stock_status();
$stock_qty = $variation->get_stock_quantity();
// The attributes taxonomy key and slug value for this variation
$attributes = $variation->get_attributes();
// Caution: Works only for 1 attribute set in the product
if(count($attributes) == 1 ) {
$attributes_keys = array_keys($attributes);
$attr_taxonomy = str_replace('attribute_', '', reset($attributes_keys) );
if( $variation->get_attribute( $attr_taxonomy ) === $term_name ) {
break; // stop the loop
}
}
$term_name .= ' - ' . $stock_status;
$term_name = $stock_qty > 0 ? $term_name . ' ('.$stock_qty.')' : $term_name;
}
return $term_name;
}
来源:https://stackoverflow.com/questions/65002729/display-variation-stock-status-on-single-dropdown-variable-products-in-wocommerc