首页 > 解决方案 > 用产品列表中的自定义链接替换产品页面链接(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 按钮。

标签: phpwordpresswoocommerce

解决方案


我修改了您在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;
}

推荐阅读