Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
WooCommerce 在多規格商品名稱上加上已售完字樣
/**
* 在多規格商品名稱上加上"已售完"字樣。
*
* @param string $option
* @param null $not_used
* @param array $attribute
* @param object $product
* @return void
*/
function add_sold_out_label_to_product_dropdown( $option, $not_used, $attribute, $product ){
$sold_out_text = __( '(已售完)', 'heromama' );
$variations = $product->get_available_variations();
$attributes = $product->get_attributes();
$attribute_slug = get_attr_slug_by_title( $attribute, $attributes );
if ( empty( $attribute_slug ) ) {
return $option;
}
foreach ( $variations as $variation ) {
if ( $variation['attributes']['attribute_' . $attribute_slug] === $option && $variation['is_in_stock'] === false ) {
$option .= $sold_out_text;
}
}
return $option;
}
add_filter( 'woocommerce_variation_option_name', 'add_sold_out_label_to_product_dropdown', 1, 4 );
/**
* 回傳 attribute taxonomy
*
* @param $attribute_title
* @param $attributes
*
* @return int|string
*/
function get_attr_slug_by_title( $attribute_title, $attributes ) {
if ( empty( $attribute_title ) || empty( $attributes ) ) {
__return_empty_string();
}
$att_slug = '';
foreach( $attributes as $tax => $tax_obj ) {
if ( $tax_obj[ 'name' ] === $attribute_title ) {
$att_slug = $tax;
}
}
return $att_slug;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment