首先,你应该检查你是否真的在更换Read more
, 您还可以删除default:
只需确保返回传递给过滤器的原始值。
如果您特别想使用switch
您可以通过设置switch(true)
然后将if语句括在括号中case
要获取/检查类别,有几种方法可以做到这一点,在下面的示例中,我使用get_the_terms
获取所有类别,然后将所有slug映射到一个数组,以便使用in_array
(为了简化示例代码,我删除了其他case语句):
add_filter( \'woocommerce_product_add_to_cart_text\', \'custom_woocommerce_product_add_to_cart_text\', 10 );
function custom_woocommerce_product_add_to_cart_text( $text ) {
// First make sure that we are only replacing \'Read more\' as some situations based on product
// this can be "Select some options" or "Add to cart"
$wc_read_more = __( \'Read more\', \'woocommerce\' );
if( $text !== $wc_read_more ){
return $text;
}
global $product;
$product_type = $product->product_type;
$product_terms = get_the_terms( $product->ID, \'product_cat\' );
// Convert to array of all the slugs
$pc_slugs = array_map( function($term){ return $term->slug; }, $product_terms );
switch ( true ) {
case ( $product_type === \'simple\' && in_array( \'services\', $pc_slugs ) ):
return __( \'Simple text\', \'woocommerce\' );
break;
}
return $text;
}
另一种选择是使用
has_term
而不是将段塞映射到阵列:
add_filter( \'woocommerce_product_add_to_cart_text\', \'custom_woocommerce_product_add_to_cart_text\', 10, 2 );
function custom_woocommerce_product_add_to_cart_text( $text, $that ) {
// First make sure that we are only replacing \'Read more\' as some situations based on product
// this can be "Select some options" or "Add to cart"
$wc_read_more = __( \'Read more\', \'woocommerce\' );
if( $text !== $wc_read_more ){
return $text;
}
global $product;
$product_type = $product->product_type;
switch ( true ) {
case ( $product_type === \'simple\' && has_term( \'services\', \'product_cat\', $product->ID ) ):
return __( \'Simple text\', \'woocommerce\' );
break;
}
return $text;
}
还想提一下你说的
if $product_type = \'simple\' && category = \'services\'
, 在PHP中,单个
=
是赋值,意思是“设置等于”,养成经常使用
==
或
===
(严格的)即使只是用哀叹的语言解释