根据 OceanWP 中的类别更改 WooCommerce "out of stock" 消息

Change WooCommerce "out of stock" message based on category in OceanWP

我只想在单个产品页面和商店存档页面上为一个类别更改 WooCommerce 中的缺货消息。

我正在使用 OceanWP 主题

这是我目前所拥有的,它可以工作,但我需要为类别添加“if”语句。

/** 
*This changes the out of stock text on the item in oceanwp theme product gallery  
*/ 
function my_woo_outofstock_text( $text ) {
    $text = __( 'Sold', 'oceanwp' );
    return $text;
}
add_filter( 'ocean_woo_outofstock_text', 'my_woo_outofstock_text', 20 );

这是我的代码尝试,基于此 ,但它仅适用于单个产品页面。有什么建议吗?

function my_woo_outofstock_text( $text, $product ) {
    $specific_categories = array( 'original-paintings' );
    
    if ( ! $product->is_in_stock() && has_term( $specific_categories, 'product_cat', $product->get_id() ) ) {
         $text = __( 'Sold', 'oceanwp' );
    }
    else {
        $text = __( 'Unavailable', 'oceanwp' );
    }        
    
    return $text;
}
add_filter( 'ocean_woo_outofstock_text', 'my_woo_outofstock_text', 20 );

您使用的过滤器挂钩仅包含 1 个参数,因此 $product 不是其中的一部分。如果您仍想对商店存档页面应用基于 $product 的更改,则应全局应用。

所以你得到:

function my_woo_outofstock_text( $text ) {
    global $product;
    
    // Add categories. Multiple can be added, separated by a comma
    $specific_categories = array( 'original-paintings' );
    
    // Is a WC product
    if ( is_a( $product, 'WC_Product' ) ) {
        // NOT in stock & has term
        if ( ! $product->is_in_stock() && has_term( $specific_categories, 'product_cat', $product->get_id() ) ) {
            $text = __( 'Sold', 'oceanwp' );
        } else {
            $text = __( 'Unavailable', 'oceanwp' );
        }  
    }
    
    return $text;
}
add_filter( 'ocean_woo_outofstock_text', 'my_woo_outofstock_text', 20, 1 );

对于单个产品页面,您可以使用 答案代码。