当 WooCommerce 单个产品有子类别时,根据产品类别在 WooCommerce 单个产品上显示内容

问题描述

我正在尝试在类别为 cat1title 或 cat2title 的任何产品页面显示下面的测试 div。使用下面的钩子,我认为是正确的,我应该在页面上看到这个 div,但我根本没有看到它。该页面显示正常,但没有 div。控制台中也没有错误。根据文档,这对于最新版本的 Woo 应该仍然有效。我错过了什么?

    add_action( 'woocommerce_single_product_summary','custom_button_by_categories',32,0 );
function custom_button_by_categories(){
    
    global $product;

    // Define your categories in this array (can be Ids,slugs or names)
    $product_cats = array('cat1title','cat2title');

    if( has_term( $product_cats,'product_cat',$product->get_id() ) ){
         //$demo_url = get_post_meta( $product->get_id(),'demo_url',true );
         echo '<div style="background: lightblue; height 1000px; width:1000px; z-index:999; position:absolute; top:0; left:0">test</div>';
    }
}

解决方法

需要在产品上设置定义的产品类别以使用 has_term() 条件函数...

因此这不适用于为产品设置了子子类别的父产品类别......

要检查父产品类别,您也可以使用此自定义条件函数:

// 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 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_action( 'woocommerce_single_product_summary','custom_button_by_categories',32,0 );
function custom_button_by_categories(){
    global $product;

    // Define your categories in this array (can be Ids,slugs or names)
    $categories = array('cat1title','cat2title');

    if( has_product_categories( $categories,$product->get_id() ) ){
         //$demo_url = get_post_meta( $product->get_id(),'demo_url',true );
         echo '<div style="background: lightblue; height 1000px; width:1000px; z-index:999; position:absolute; top:0; left:0">test</div>';
    }
}

代码位于活动子主题(或活动主题)的functions.php 文件中。