php - 用产品列表中的自定义链接替换产品页面链接(woocommerce)
问题描述
我只有2个产品。我想在产品列表页面上提供每个产品的自定义链接。
我正在使用下面的代码...
add_action('woocommerce_after_shop_loop_item', 'add_a_custom_button', 5 );
function add_a_custom_button() {
global $product;
if (is_product() == 3557 || is_shop() || is_product_category() || is_product_tag()):
?>
<div style="margin-bottom:10px;">
<a class="button custom-button" href="https://example.com/redirect/3557/">Buy @ Store1</a>
</div>
<?php
endif;
if (is_product() == 3541 || is_shop() || is_product_category() || is_product_tag()):
?>
<div style="margin-bottom:10px;">
<a class="button custom-button" href="https://example.com/redirect/3541/">Buy @ Store2</a>
</div>
<?php
endif;
上面代码的问题在于它显示了每个产品的两个 html 按钮。
解决方案
我修改了您在woocommerce_after_shop_loop_item
动作挂钩中使用的代码。您可以通过$product->get_id()
.
add_action( 'woocommerce_after_shop_loop_item', 'add_a_custom_button', 5 );
function add_a_custom_button() {
global $product;
if ( $product->get_id() == 3557 && ( is_shop() || is_product_category() || is_product_tag() ) ): ?>
<div style="margin-bottom:10px;">
<a class="button custom-button" href="https://example.com/redirect/3557/">Buy @ Store1</a>
</div>
<?php
endif;
if ( $product->get_id() == 3541 && ( is_shop() || is_product_category() || is_product_tag() ) ): ?>
<div style="margin-bottom:10px;">
<a class="button custom-button" href="https://example.com/redirect/3541/">Buy @ Store2</a>
</div>
<?php
endif;
}
此外,如果您想更改循环产品默认链接,您可以使用woocommerce_loop_product_link
过滤器挂钩。
add_filter( 'woocommerce_loop_product_link', 'change_product_permalink_based_on_product', 99, 2 );
function change_product_permalink_based_on_product( $link, $product ) {
if ( $product->get_id() === 3557 ){
$link = 'https://example.com/redirect/3557/';
}
if ( $product->get_id() === 3541 ){
$link = 'https://example.com/redirect/3541/';
}
return $link;
}
推荐阅读
- javascript - 从 react 使用效果/钩子导出函数/方法
- ruby-on-rails - 如果报告为空白或数据为零,我需要引发异常
- flutter - 使用按钮和滚动将小部件添加到 GridView 时出现问题
- angularjs - 自定义指令在保留原始值的同时屏蔽敏感数据
- macos - 添加终端以停靠持久应用程序,默认写入外语 macOS
- powerbi - 在 Power BI 中仅过滤折线图上的一个值/折线
- python - 我想在按下pick时实现on_touch_down函数,但不知道如何实现
- java - 当存在来自超类的依赖注入时,如何设置测试?
- ruby-on-rails - 如何在后端 Rails 电子邮件中包含一个链接,该链接直接进入 ios 应用程序,例如忘记密码
- javascript - Mozilla 扩展警报每 30 分钟一次