在单个产品页面上的 "added to cart" 消息内的主类别中添加带有 link 的自定义按钮

Add custom button with link to main category inside "added to cart" message on single product page

如何在当前产品的单个产品页面上的“添加到购物车”消息中的主类别中添加带有 link 的自定义按钮。

为了清楚自定义按钮的位置,请参见图片:


我知道如何将带 link 的按钮添加到主商店页面。

add_filter( 'wc_add_to_cart_message_html', 'my_custom_add_to_cart_message' );
function my_custom_add_to_cart_message( $message ) {
    $message .= sprintf( '<a href="%s" class="button wc-forward back-to-shop" style="margin-right: 15px;">%s</a>', get_permalink( woocommerce_get_page_id( 'shop' ) ), 'Continue');
    return $message;
}

但我不知道如何将 link 设为最后或主要产品类别。

使用 Woocommerce Continue Shopping Button Link to Last Product Category Page 答案代码对我不起作用,因为它不是我想要的。

要在主类别中添加带有 link 的按钮,在单个产品页面的“产品已添加到购物车消息”中,您可以使用:

function filter_wc_add_to_cart_message ( $message, $product_id ) {
    // Retrieves the terms for a post
    $terms = wp_get_post_terms( $product_id, 'product_cat', array( 'include_children' => false ) );

    // First main product category
    $term = reset( $terms );

    // Link
    $term_link = get_term_link( $term->term_id, 'product_cat' );
    
    // Button
    $term_button = '<a href="' . $term_link . '" class="button">My button</a>'; 
    
    return $message . $term_button;
}
add_filter( 'wc_add_to_cart_message', 'filter_wc_add_to_cart_message', 10, 2 );

注意:可能需要自定义 CSS 和较小的 html 更改,具体取决于主题