根据 WooCommerce 中的产品类别自定义 "Out of stock" 文本

Custom "Out of stock" text based on product category in WooCommerce

每个缺货产品都显示“缺货”

有很多 functions.php 脚本可以覆盖文本,但我只是想覆盖特定于“类别 A”的文本,或者如果我知道类别“id”编号,那也可以。

我找到了这个脚本,但它只允许您修改每个产品 ID 的 txt。

add_filter( 'woocommerce_get_availability', 'wcs_custom_get_availability', 10, 2);       
function wcs_custom_get_availability( $availability, $_product ) { 
    // custom 
    if ( $_product->is_in_stock() && $_product->get_id() == '6498' ) {
        $availability['availability'] = sprintf( __('✔️ Available but low in stock | 30-day No Questions Asked Money-Back Guarantee Applies', 'woocommerce'), $_product->get_stock_quantity());
    }

    // Out of stock
    if ( ! $_product->is_in_stock() ) {
        $availability['availability'] = __('Sorry, All sold out!', 'woocommerce');
    }

    return $availability;
}

如何根据类别进一步调整此脚本?

要检查产品类别,您可以使用 has_term()

has_term( string|int|array $term = '', string $taxonomy = '', int|WP_Post $post = null )

检查当前 post 是否有任何给定的术语。


所以你得到:

function filter_woocommerce_get_availability( $availability, $product ) {
    // Specific categories
    $specific_categories = array( 'Categorie-A', 'categorie-1' );
    
    // Out of stock and has certain category     
    if ( ! $product->is_in_stock() && has_term( $specific_categories, 'product_cat', $product->get_id() ) ) {
        $availability['availability'] = __('My custom text', 'woocommerce' );
    }

    return $availability;
}
add_filter( 'woocommerce_get_availability', 'filter_woocommerce_get_availability', 10, 2 );