I currently run a site which has products in Woocommerce. The product URL links to an affiliate site and the custom functions.php script appends the affiliate ID to the extenal URL using this code:
* Custom Add Affiliate link to Buy Product
*/
add_filter( 'woocommerce_product_add_to_cart_url', 'custom_product_add_to_cart_url', 20, 2 );
function custom_product_add_to_cart_url( $add_to_cart_url, $product ){
if( $product->is_type('external') )
$add_to_cart_url .= '/?affiliateID-1';
return $add_to_cart_url;
}
/**
* End Custom Add Affiliate link to Buy Product
What I am hoping to do is add another affilate site to this and depending which URL is in the $add_to_cart_url
would determine which affiliate link is appended.
So currently if the $add_to_cart_url is www.siteA.com the link generated is www.siteA.com/?affiliateID-1
I want to make a change so that:
if the $add_to_cart_url is www.siteA.com the link generated is www.siteA.com/?affiliateID-1 OR if the $add_to_cart_url is www.siteB.net the link generated is www.siteB.net/?affiliateID-2
I assume I need some form of "if $add_to_cart_url is this, then append with this, else append with this" however I'm not sure how I need to adjust my existing code to do this.
I'm hoping someone out there can help me.
Many thanks.
$add_to_cart = $someValueHere;
if ($add_to_cart == $siteAValue){
$add_to_cart_url .= '/?affiliateID-1';
} else if ($add_to_cart == $siteBValue){
$add_to_cart_url .= '/?affiliateID-2';
}
return $add_to_cart_url;
}
Where should I be entering the specifics of each of the 2 urls it needs to check against? Maybe if for example Facebook.com is affiliate 1 and Microsoft.com is affiliate 2? Would you be able to show an example?
CodePudding user response:
You can try something like this
add_filter( 'woocommerce_product_add_to_cart_url', 'custom_product_add_to_cart_url', 20, 2 );
function custom_product_add_to_cart_url( $add_to_cart_url, $product ){
if( !$product->is_type('external') ){
return $add_to_cart_url;
}
if (strpos($add_to_cart_url, 'www.sitea.com/') === 0) {
$add_to_cart_url .= '/?affiliateID-1';
} elseif (strpos($add_to_cart_url, 'www.siteb.com/') === 0) {
$add_to_cart_url .= '/?affiliateID-2';
}
return $add_to_cart_url;
}