Woocommerce 商店页面和档案中的附加按钮

Additional button in Woocommerce shop page and archives

我想在产品页面上的 "Add to Cart" 旁边添加一个按钮,点击后会向产品 URL 添加“-sample”。

示例:

您正在查看产品 1 的页面,URL 是“http://www.example.com/shop/product-1/

当您点击该按钮时,它会将“-sample”添加到 URL “http://www.example.com/shop/product-1-sample/

我怎样才能做到这一点?

谢谢

对于 woocommerce 3+ (仅限):

在 woocommerce 3 中,您将改用 woocommerce_after_shop_loop_item 操作挂钩,因为挂钩 woocommerce_after_add_to_cart_button 将不再起作用。

add_action( 'woocommerce_after_add_to_cart_button', 'add_custom_button', 10, 0 );
function add_custom_button() {
    global $product;

    $product_link = $product->get_permalink();

    $sample_link = substr($product_link, 0, -1) . '-sample/';
    echo '<a class="button alt btn-sample" href="' . esc_url( $sample_link ) .'">' . __( "Get a sample", "my_theme_slug" )  . '</a>';
}

代码继续在您的活动子主题(或活动主题)的 function.php 文件中。已测试并有效。


在 woocommerce 3 之前:

这可以使用挂钩 woocommerce_after_add_to_cart_button 在产品页面上添加您的附加按钮,使用此自定义函数:

add_action( 'woocommerce_after_add_to_cart_button', 'add_custom_button', 10, 0 );
function add_custom_button() {
    global $product;

    $product_link = get_permalink( get_the_id() );

    $sample_link = substr($product_link, 0, -1) . '-sample/';
    echo '<a class="button alt btn-sample" href="' . esc_url( $sample_link ) .'">' . __( "Get a sample", "my_theme_slug" )  . '</a>';
}

此代码在您的活动子主题或主题的 function.php 文件中。

此代码已经过测试并且功能齐全。


基于此:Add a button after add to cart and redirect it to some custom link in WooCommerce

还有这个:PHP - How to remove all specific characters at the end of a string?

距离最初的问题已经过去很长时间了,但这是对我有用的最新更新,WooCommerce 6.3.1:

/* WooCommerce customization */
add_action( 'woocommerce_after_shop_loop_item', 'custom_select_link', 11 );
function custom_select_link() {
     global $product;
     // Custom "Select" button.
     echo '<a class="custom-button" href="' . esc_url( get_permalink( $product->id ) ) . '"><button class="custom-button">   </button></a>';
} 

这个答案引用了wordpress.stackexchange.

中的一个答案