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

WordPress WooCommerce在每个产品按钮上显示产品类别

  •  1
  • Squish  · 技术社区  · 8 年前

    在Woocommerce中,每个产品按钮默认为产品图像、产品名称、价格和“添加到购物车”按钮。但是,我想在每个产品按钮中添加该产品所属的类别(这将引导用户进入类别页面)。

    enter image description here

    1 回复  |  直到 8 年前
        1
  •  1
  •   LoicTheAztec    8 年前

    这可以使用连接在 woocommerce_loop_add_to_cart_link

    // Shop pages: we replace the button add to cart by a link to the main category archive page
    add_filter( 'woocommerce_loop_add_to_cart_link', 'custom_text_replace_button', 10, 2 );
    function custom_text_replace_button( $button, $product ) {
        // Get the product categories  IDs
        $category_ids = $product->get_category_ids();
    
        // return normal button if no category is set or if is not a shop page
        if( empty($category_ids) || ! is_shop() ) return $button;
    
        // Iterating through each product category
        foreach( $product->get_category_ids() as $category_id ){
            // The product category WP_Term object
            $term_obj = get_term_by( 'id', $category_id, 'product_cat' );
            // Only for first main category
            if( $term_obj->parent == 0 ){
                break; // we stop the loop
            }
        }
    
        // The custom button below
        $button_text = __("Visit", "woocommerce") . ' ' . $term_obj->name;
        $button_link = get_term_link( $term_obj->slug, 'product_cat' );
        return '<a class="button" href="' . $button_link . '">' . $button_text .'</a>';
    }
    

    代码进入函数。活动子主题(或主题)或任何插件文件中的php文件。

    这段代码经过测试并在woocommerce版本3上运行+