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

时间:2018-07-08 23:16:02

标签: php wordpress woocommerce hook-woocommerce custom-taxonomy

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

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 :(得分: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;
}

答案 1 :(得分: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

相关问题