Reputation: 11
I have only 2 products. I want to provide custom link to each respective product on product listing page.
I am using below code...
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;
The issue with above code is that it shows both html buttons for each product.
Upvotes: 1
Views: 812
Reputation: 11282
I revised your code that you use in woocommerce_after_shop_loop_item
action hook. You can get prodcut id by $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;
}
Also if you want to change the loop product default link you can use the woocommerce_loop_product_link
filter hook.
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;
}
Upvotes: 1