基于Woocommerce中产品类别的自定义产品价格后缀

时间:2018-11-22 16:44:15

标签: php wordpress woocommerce custom-taxonomy price

我需要在大多数在线目录的价格上添加“每米”,我在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;
}

我希望每米显示“织物”,“小百货”,“衬里”,而不显示“扣件”,“补丁”,“残料”。

我尝试过代码的变体-我的排除项在顶部,第二部分的包含项,有/无“(!具有词条”部分,但是无论我采取哪种方式,都会删除所有后缀消息,或者适用于所有类别。

如果我能够像以前使用的非常膨胀的插件那样使它正常工作,那将是惊人的。我基本上只具备这方面的能力,因此请随意谈论我,就像我是白痴一样。

1 个答案:

答案 0 :(得分:1)

has_term()函数中的代码中有一些错误。

要处理父产品类别,我们将使用自定义条件函数而不是has_tem()

我还添加了一些代码以处理可变产品的产品变化选定价格,因此,请尝试以下操作:

// Custom conditional function that checks for parent product categories
function has_product_categories( $categories, $product_id ) {
     // Initializing
    $parent_term_ids = $categories_ids = array();
    $taxonomy        = 'product_cat';

    // Convert categories term names and slugs to categories term ids
    foreach ( $categories as $category ){
        if( is_numeric( $category ) ) {
            $categories_ids[] = (int) $category;
        } elseif ( term_exists( sanitize_title( $category ), $taxonomy ) ) {
            $categories_ids[] = get_term_by( 'slug', sanitize_title( $category ), $taxonomy )->term_id;
        }
    }

    // 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文件中。经过测试并可以正常工作。

enter image description here