Skip to content

Instantly share code, notes, and snippets.

@EricBusch
Last active September 1, 2017 14:25
Show Gist options
  • Save EricBusch/ed9a2573d7ba7851425bbfd457f98017 to your computer and use it in GitHub Desktop.
Save EricBusch/ed9a2573d7ba7851425bbfd457f98017 to your computer and use it in GitHub Desktop.
Forces the insertion of your affiliate ID into the affiliate link even if the Datafeedr API plugin has been deactivated or uninstalled. [datafeedr][dfrapi][dfrpswc]
<?php
/**
* Forces the insertion of your affiliate ID into the affiliate link even
* if the Datafeedr API plugin has been deactivated or uninstalled.
*
* This should be added to your My Custom Code plugin.
* @link https://datafeedrapi.helpscoutdocs.com/article/32-creating-your-own-custom-plugin
*
* @see mycode_dfrapi_url()
*
* @param string $url The URL for the External product.
* @param WC_Product $product
*
* @return string Updated $url.
*/
add_filter( 'woocommerce_product_get_product_url', 'mycode_force_insert_affiliate_id', 20, 2 );
function mycode_force_insert_affiliate_id( $url, WC_Product $product ) {
if ( ! is_a( $product, 'WC_Product_External' ) ) {
return $url;
}
$post_id = $product->get_id();
$dfrps_product = get_post_meta( $post_id, '_dfrps_product', true );
if ( empty( $dfrps_product ) ) {
return $url;
}
$url = mycode_dfrapi_url( $dfrps_product );
return $url;
}
/**
* This inserts the affiliate ID into a product's URL.
*
* @see dfrapi_url() in the Datafeedr API plugin.
* @link https://plugins.trac.wordpress.org/browser/datafeedr-api/trunk/functions/functions.php
*
* @param array $product Datafeedr product array.
*
* @return string Affiliate link with affiliate ID and optionally tracking ID.
*/
function mycode_dfrapi_url( $product ) {
// Get all the user's selected networks.
$networks = (array) get_option( 'dfrapi_networks' );
// Extract the affiliate ID from the $networks array.
$affiliate_id = ( isset( $networks['ids'][ $product['source_id'] ]['aid'] ) ) ? $networks['ids'][ $product['source_id'] ]['aid'] : '';
$affiliate_id = trim( $affiliate_id );
// Extract the Tracking ID from the $networks array.
$tracking_id = ( isset( $networks['ids'][ $product['source_id'] ]['tid'] ) ) ? $networks['ids'][ $product['source_id'] ]['tid'] : '';
$tracking_id = trim( $tracking_id );
// Determine which URL field to get: 'url' OR 'ref_url'. Return 'url' if $tracking_id is empty, otherwise, use 'ref_url'.
$url = ( $tracking_id == '' ) ? $product['url'] : $product['ref_url'];
// Replace placeholders in URL.
$placeholders = array( "@@@", "###" );
$replacements = array( $affiliate_id, $tracking_id );
$url = str_replace( $placeholders, $replacements, $url );
return $url;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment