首页 文章

将产品类别链接按钮添加到Woocommerce单个产品页面

提问于
浏览
1

我正在尝试添加指向单个产品页面的链接,该链接可以追溯到该产品的类别页面

add_action ('woocommerce_before_single_product','add_backbtn_fcategory', 5);

function add_backbtn_fcategory(){

$category_id = get_cat_ID();

$category_link = get_category_link( $category_id );

?>

<a href="<?php echo esc_url( $category_link ); ?>" title="Category Name">BACK</a>

<?php
}

这样做的结果是,单个产品页面不会在放置函数的钩子下面呈现

2 回答

  • 0
    global $woocommerce,$product;
    
    $product_category_ids = wc_get_product_term_ids( $product->get_id(), 'product_cat' );
    
    foreach( $product_category_ids as $cat_id ) {
        $term = get_term_by( 'id', $cat_id, 'product_cat' );
    
        echo $term->name;
    }
    
  • 0

    由于您可以为产品设置许多产品类别,因此您将使用以下(注释):

    add_action ('woocommerce_before_single_product','add_back_product_category_button', 5);
    function add_back_product_category_button(){
    
        // Get the product categories set in the product
        $terms = wp_get_post_terms( get_the_id(), 'product_cat' );
    
        // Check that there is at leat one product category set for the product
        if(sizeof($terms) > 0){
            // Get the first product category WP_Term object
            $term = reset($terms);
            // Get the term link (button link)
            $link = get_term_link( $term, 'product_cat' );
    
            // Button text
            $text = __('Back to','woocommerce') . ' <strong>' . $term->name . '</strong>';
    
            // Output
            echo '<p><a href="'.esc_url($link).'" title="'.$text.'" class="button '.$term->slug.'">'.$text.'</a></p>';
        }
    }
    

    代码位于活动子主题(或活动主题)的function.php文件中 . 经过测试和工作 .

    enter image description here

相关问题