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

Display content on WooCommerce single products based on product categories when they have child categories

我正在尝试在类别 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 文件。