我需要在大多数在线目录的价格中添加“每米”,我在我的 finctions.php 中尝试了this thread上的代码,但我无法让它省略/包含特定类别 - 这似乎是全部或无。我究竟做错了什么?
我已经编辑了代码:
/*add 'per metre' after selected items*/
add_filter( 'woocommerce_get_price_html', 'conditional_price_suffix', 20, 2 );
function conditional_price_suffix( $price, $product ) {
// HERE define your product categories (can be IDs, slugs or names)
$product_categories = array('fabric','haberdashery', 'lining',);
if( ! has_term( $product_categories, 'fasteners', 'patches', 'remnnants', $product->get_id() ) )
$price .= ' ' . __('per metre');
return $price;
}
我希望“面料”、“小百货”、“衬里”以每米显示,而“紧固件”、“补丁”、“残余物”不显示后缀。
我尝试过代码的变体 - 我在顶部位中的排除项和第二部分中的包含项,以及带/不带“(!有术语”部分,但无论我做什么都会带走所有后缀消息,或适用于所有类别。
如果我能让它像以前使用一个非常臃肿的插件一样工作,那就太棒了。我在这方面的能力只是基本的,所以请随意跟我讲讲,就好像我是个白痴一样。
has_term()
函数中的代码有一个小错误。为了处理父产品类别,我们将使用自定义条件函数而不是
has_tem()
。我还添加了一些代码
来处理可变产品的产品变体选择价格,所以试试这个:
// Custom conditional function that handle parent product categories too
function has_product_categories( $categories, $product_id = 0 ) {
$parent_term_ids = $categories_ids = array(); // Initializing
$taxonomy = 'product_cat';
$product_id = $product_id == 0 ? get_the_id() : $product_id;
if( is_string( $categories ) ) {
$categories = (array) $categories; // Convert string to array
}
// Convert categories term names and slugs to categories term ids
foreach ( $categories as $category ){
$result = (array) term_exists( $category, $taxonomy );
if ( ! empty( $result ) ) {
$categories_ids[] = reset($result);
}
}
// Loop through the current product category terms to get only parent main category term
foreach( get_the_terms( $product_id, $taxonomy ) as $term ){
if( $term->parent > 0 ){
$parent_term_ids[] = $term->parent; // Set the parent product category
$parent_term_ids[] = $term->term_id; // (and the child)
} else {
$parent_term_ids[] = $term->term_id; // It is the Main category term and we set it.
}
}
return array_intersect( $categories_ids, array_unique($parent_term_ids) ) ? true : false;
}
add_filter( 'woocommerce_get_price_html', 'conditional_price_suffix', 10, 2 );
function conditional_price_suffix( $price, $product ) {
// Handling product variations
$product_id = $product->is_type('variation') ? $product->get_parent_id() : $product->get_id();
// HERE define your product categories (can be IDs, slugs or names)
$product_categories = array('fabric','haberdashery', 'lining');
if( has_product_categories( $product_categories, $product_id ) )
$price .= ' ' . __('per metre');
return $price;
}
代码位于活动子主题(或活动主题)的 function.php 文件中。经过测试并有效。