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

Posted

技术标签:

【中文标题】Woocommerce 商店页面和档案中的附加按钮【英文标题】:Additional button in Woocommerce shop page and archives 【发布时间】:2016-12-17 15:37:36 【问题描述】:

我想在产品页面上的“添加到购物车”旁边添加一个按钮,单击该按钮会在产品 URL 中添加“-sample”。

例子:

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

当您单击按钮时,它会在 URL 中添加“-sample” "http://www.example.com/shop/product-1-sample/"

我怎样才能做到这一点?

谢谢

【问题讨论】:

【参考方案1】:

对于 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 更新后停止工作,知道为什么吗? 实际上,这是我添加的代码,仅将按钮应用于某个类别,当我删除此代码时,它再次起作用。 Here's the Code Link to new question 是否可以将此添加到商店页面而不是产品页面? @DiegoM。见:***.com/questions/38887186/…

以上是关于Woocommerce 商店页面和档案中的附加按钮的主要内容,如果未能解决你的问题,请参考以下文章

单个产品页面上的 Woocommerce 钩子溢出

仅在商店中用 woocommerce 中的贝宝结帐替换添加到购物车按钮

将添加到购物车按钮替换为链接到 WooCommerce 3 中商店页面上的产品页面的更多内容

在 WooCommerce 商店页面上向 Ajax 添加数量字段添加到购物车按钮

css 隐藏WooCommerce中商店/类别页面的“选择选项”按钮

通过 WooCommerce 产品设置中的自定义复选框将类添加到 WooCommerce 页面