代码之家  ›  专栏  ›  技术社区  ›  danish

如何根据产品类别在woocommerce产品页面上添加链接?

  •  0
  • danish  · 技术社区  · 6 年前

    我能够在woocommerce产品页面上找到添加链接的代码,但我想根据产品类别添加链接。下面是我为在产品页面上显示链接而添加的代码。有人能帮我获取代码,按照产品类别将链接添加到产品页面吗?

    add_action( 'woocommerce_before_add_to_cart_button', 
    'content_before_addtocart_button' );
    
    function content_before_addtocart_button() {
    echo '<div class="content-section">add custom size <a 
     href="http://google.com">here</a></div>';
    }
    
    1 回复  |  直到 6 年前
        1
  •  1
  •   Andrew Schultz    6 年前

    将此代码放入函数中。如果类别slug与此实例中的“jackets”匹配,它将输出一个链接。

    add_action( 'woocommerce_before_add_to_cart_button', 'content_before_addtocart_button' );
    
    function content_before_addtocart_button() {
        global $post;
    
        $terms = get_the_terms( $post->ID, 'product_cat' );
    
        foreach ($terms as $term) {
            if( $term->slug === 'jackets')
                echo '<div class="content-section">add custom size <a href="' . esc_url( get_term_link( $term->term_id, 'product_cat' ) ) . '">' . $term->name . '</a></div>';
        }
    }