基于产品类型的 WooCommerce“添加到购物车"按钮旁边的自定义按钮

2021-12-22 00:00:00 jquery php javascript wordpress woocommerce

我想根据产品类型在 WooCommerce 的添加到购物车"按钮旁边添加一个自定义按钮查看演示",无论是在主商店页面还是单个产品页面上.

I want add a custom Button "View Demo" next to "Add to Cart" button of WooCommerce based on Product Type, both on main shop page and single product page.

我已经完成了以下步骤:

I've done this steps:

添加代码到主题文件header.php:

<script>var url_demo = "<?php echo the_field('url_demo'); ?>"</script>

使用TC Custom JavaScript"插件添加 jQuery 脚本:

Add jQuery script using "TC Custom JavaScript" plugin:

jQuery(function($) {
 $('.add_to_cart_button, .single_add_to_cart_button').after(' <a class="button demo_button" style="padding-right: 0.75em;padding-left: 0.75em;margin-left: 8px; background-color: #0ebc30;" href="'+url_demo+'" target="_blank">View Demo</a>');
});

它的工作,主商店页面和单个产品页面上显示的自定义按钮查看演示".

It's work, the Custom button "View Demo" shown on main shop page and single product page.

但我现在遇到了一些问题,查看演示"按钮链接仅在单个产品页面上正确,而在商店主页上的查看演示"按钮链接到相同的网址.我上面的代码有错吗?

But I've some problem now, the "View Demo" button link only correct on Single Product page, while on shop main page the "View Demo" button, link to the same url. Is my code above wrong?

我的问题是,如何添加仅针对特定产品类型显示的查看演示"按钮(在主商店页面和单个产品页面上),例如仅在类别主题上显示?最后,有没有其他方法可以像上面的方法一样在不编辑 header.php 文件的情况下添加演示链接?我只是期待 header.php 文件在主题更新时重置.

My questions are, how to add "View Demo" button (both on main shop page and single product page) that only show for spesific product type, for example only show on category Theme? Last, is there any other way to add demo link without editing the header.php file like above method? I just anticipating the header.php file reset if the theme updated.

推荐答案

我正在使用另一种方法:WooCommerce hooks.

I am using another way to do it: WooCommerce hooks.

您不再需要 jQuery 脚本以及位于 header.php 文件中的 javascript,因此您可以删除它们.

You don't need anymore the jQuery script and also the javascript located in your header.php file, so you can erase them.

使用 get_field() 而不是 the_field(感谢 Deeptichipdey) 只获取在 echoed 字符串中连接的值.

Using get_field() instead of the_field (thanks to Deepti chipdey) to get only the value concatenated in the echoed string.

将此代码片段粘贴到位于活动子主题或主题文件夹中的 function.php 文件中:

Paste this code snippet in your function.php file located in your active child theme or theme folder:

function wc_shop_demo_button() {
    echo '<a class="button demo_button" style="padding-right: 0.75em;padding-left: 0.75em;margin-left: 8px; background-color: #0ebc30;" href="'.get_field( "url_demo" ).'" target="_blank">View Demo</a>';
}
add_action( 'woocommerce_after_shop_loop_item', 'wc_shop_demo_button', 20 );
add_action( 'woocommerce_after_add_to_cart_button', 'wc_shop_demo_button', 20 );

我已经瞄准了用于在商店页面和单个产品页面上显示添加到购物车按钮的钩子,在它之后显示您的查看演示按钮,购买降低优先.

I have target the hooks used to display Add to cart button on shop page and in single product pages, to display your View demo button after it, buy lowering the priority.

相关文章