How to add Affiliate Links to Woocommerce Variations

Posted by & filed under Tutorials, Uncategorized, Web Design Tutorials, Wordpress.

How to add Affiliate Links to Woocommerce Variations was last modified: January 23rd, 2014 by Derek Schmidt

Recently we had a request from someone who wanted to add affiliate links to Woocommerce variations so we thought we would put together this quick tutorial to show you how to do that.

First, we need to have a way to input our links in the Woocommerce admin panel when the product type is “variable”. The best way I thought to achieve this would be to add a custom meta box to each variation box when the variations were set. Luckily someone had already done some leg work on this so we were able to use some of their code found here.

So in order to create our custom meta boxes for variations we need to start working with our themes functions.php file and start by adding some actions that will handle our magic, like so:

// Display Fields
add_action( 'woocommerce_product_after_variable_attributes', 'variable_fields', 10, 2 );
//JS to add fields for new variations
add_action( 'woocommerce_product_after_variable_attributes_js', 'variable_fields_js' );
// Save Fields
add_action( 'woocommerce_process_product_meta_variable', 'variable_fields_process', 10, 1 );

Great! We have plugged into the hooks that are going to handle our data handling, now we just need to create the functions that are going to assist that. So right below where we just added the hooks in our functions file, lets go ahead and create those functions.

function variable_fields( $loop, $variation_data ) {

}

function variable_fields_js() {

}

function variable_fields_process( $post_id ) {

}

Note: Notice the parameters we are passing through those functions. ie $loop, $variation_data, $post_id.

Now that we have our functions set we need to setup what is going to be inside of each one. Let’s start by creating our meta box, in this case I am going to use ‘_my_affiliate_url’ as the meta value, and of course the meta key would be the variation id (we will get into that more later).

So looking at the first two functions we created, we are going to place our code inside those two functions so it looks like this:

function variable_fields( $loop, $variation_data ) {
?>	
	<tr>
		<td>
			<div>
					<label><?php _e( 'Affiliate URL', 'woocommerce' ); ?></label>
					<input type="text" size="5" name="my_affiliate_url[<?php echo $loop; ?>]" value="<?php echo $variation_data['_my_affiliate_url'][0]; ?>"/>

			</div>
		</td>
	</tr>
<?php
}

function variable_fields_js() {
?>
<tr>
		<td>
			<div>
					<label><?php _e( 'My Custom Field', 'woocommerce' ); ?></label>
					<input type="text" size="5" name="my_affiliate_url[' + loop + ']" />
			</div>
		</td>
	</tr>
<?php
}

All this does is create our custom meta boxes for each Woocommerce variation. Login to the backend of your site and look at a variable product (click on Variations and expand each one) and you will see our new meta box. Except when you put info in there, it doesnt do anything, so we need to setup our function “variable_fields_process” so that it can save the data we enter in there.

Let’s do that now:

function variable_fields_process( $post_id ) {
	if (isset( $_POST['variable_sku'] ) ) :
		$variable_sku = $_POST['variable_sku'];
		$variable_post_id = $_POST['variable_post_id'];
		$variable_custom_field = $_POST['my_affiliate_url'];
		for ( $i = 0; $i < sizeof( $variable_sku ); $i++ ) :
			$variation_id = (int) $variable_post_id[$i];
			if ( isset( $variable_custom_field[$i] ) ) {
				update_post_meta( $variation_id, '_my_affiliate_url', stripslashes( $variable_custom_field[$i] ) );
			}
		endfor;
	endif;
}

Now we can enter our info in there and once the page refreshes we see that the info does save and show in the meta boxes.

Now we need to know how to show that info on the front-end of the website or in our case pass the info into our “Add to Cart” button so it will take the user to the appropriate affiliate link.

*If you dont plan on using affiliate links or are using these meta boxes for some other info that you need to display on the front – end of your website you can simply use this to get the meta_value for each variation:

$variations = $product->get_available_variations();
		foreach ($variations as $key => $value) {
			echo get_post_meta($value['variation_id'], '_my_affiliate_url', true);
		}

So what if we are using these for Affiliate links for variations? Well the best way I thought to do that would be to remove the default select box Woocommerce uses to house its variations and instead show them in a table format so each add to cart link is easy to view and handled appropriately. So finally, let’s set that up so that we can create that table and have each add to cart button link to each variations affiliate url.

To do this we need to add this last piece of code to our functions.php file underneath where we have been working:

//front-end variations
function woocommerce_variable_add_to_cart() {
		global $product, $post;
		$variations = $product->get_available_variations();
		foreach ($variations as $key => $value) {
		?>
		<form action="<?php echo esc_url( $product->add_to_cart_url() ); ?>"method="post" enctype='multipart/form-data'>
			<input type="hidden" name="variation_id" value="<?php echo $value['variation_id']?>" />
			<input type="hidden" name="product_id" value="<?php echo esc_attr( $post->ID ); ?>" />
			<?php
			if(!empty($value['attributes'])){
				foreach ($value['attributes'] as $attr_key => $attr_value) {
				?>
				<input type="hidden" name="<?php echo $attr_key?>" value="<?php echo $attr_value?>">
				<?php
				}
			}
			?>
			<table>
				<tbody>
					<tr>
						<td>
							<b><?php echo implode('/', $value['attributes']);?></b>
						</td>
						<td>
							<?php echo $value['price_html'];?>
						</td>
						<td>
							<a class="single_add_to_cart_button button alt" target="_blank" href="<?php echo get_post_meta($value['variation_id'], '_my_affiliate_url', true); ?>" ><?php echo apply_filters('single_add_to_cart_text', __( 'Add to cart', 'woocommerce' ), $product->product_type); ?></a>
						</td>
					</tr>
				</tbody>
			</table>
		</form>
		<?php
		}
}

So in the above code you will notice that we have completely removed the actual button[type=”submit”] that Woocommerce uses but replace it with a basic anchor link while keeping the classes in tact so that it looks like the default Woocommerce Add to Cart button. We have assigned the href to grab our meta_value for EACH variation, and open it in a new tab.

When you have done all of this your completed code in your functions.php file should look like this:

// Display Fields
add_action( 'woocommerce_product_after_variable_attributes', 'variable_fields', 10, 2 );
//JS to add fields for new variations
add_action( 'woocommerce_product_after_variable_attributes_js', 'variable_fields_js' );
// Save Fields
add_action( 'woocommerce_process_product_meta_variable', 'variable_fields_process', 10, 1 );

function variable_fields( $loop, $variation_data ) {
?>	
	<tr>
		<td>
			<div>
					<label><?php _e( 'Affiliate URL', 'woocommerce' ); ?></label>
					<input type="text" size="5" name="my_affiliate_url[<?php echo $loop; ?>]" value="<?php echo $variation_data['_my_affiliate_url'][0]; ?>"/>

			</div>
		</td>
	</tr>
<?php
}

function variable_fields_js() {
?>
<tr>
		<td>
			<div>
					<label><?php _e( 'My Custom Field', 'woocommerce' ); ?></label>
					<input type="text" size="5" name="my_affiliate_url[' + loop + ']" />
			</div>
		</td>
	</tr>
<?php
}

function variable_fields_process( $post_id ) {
	if (isset( $_POST['variable_sku'] ) ) :
		$variable_sku = $_POST['variable_sku'];
		$variable_post_id = $_POST['variable_post_id'];
		$variable_custom_field = $_POST['my_affiliate_url'];
		for ( $i = 0; $i < sizeof( $variable_sku ); $i++ ) :
			$variation_id = (int) $variable_post_id[$i];
			if ( isset( $variable_custom_field[$i] ) ) {
				update_post_meta( $variation_id, '_my_affiliate_url', stripslashes( $variable_custom_field[$i] ) );
			}
		endfor;
	endif;
}

//front-end variations
function woocommerce_variable_add_to_cart() {
		global $product, $post;
		$variations = $product->get_available_variations();
		foreach ($variations as $key => $value) {
		?>
		<form action="<?php echo esc_url( $product->add_to_cart_url() ); ?>"method="post" enctype='multipart/form-data'>
			<input type="hidden" name="variation_id" value="<?php echo $value['variation_id']?>" />
			<input type="hidden" name="product_id" value="<?php echo esc_attr( $post->ID ); ?>" />
			<?php
			if(!empty($value['attributes'])){
				foreach ($value['attributes'] as $attr_key => $attr_value) {
				?>
				<input type="hidden" name="<?php echo $attr_key?>" value="<?php echo $attr_value?>">
				<?php
				}
			}
			?>
			<table>
				<tbody>
					<tr>
						<td>
							<b><?php echo implode('/', $value['attributes']);?></b>
						</td>
						<td>
							<?php echo $value['price_html'];?>
						</td>
						<td>
							<a class="single_add_to_cart_button button alt" target="_blank" href="<?php echo get_post_meta($value['variation_id'], '_my_affiliate_url', true); ?>" ><?php echo apply_filters('single_add_to_cart_text', __( 'Add to cart', 'woocommerce' ), $product->product_type); ?></a>
						</td>
					</tr>
				</tbody>
			</table>
		</form>
		<?php
		}
}

There you go, hope that helps you with understanding how custom meta fields work in Woocommerce and how to apply them to your shop. Happy theming :-)

Additional Resources:
Custom Fields in WordPress
get_post_meta – Codex
update_post_meta – Codex

Like this? Share it with your friends!
Facebook Twitter Linkedin Email

How to add Affiliate Links to Woocommerce Variations was last modified: January 23rd, 2014 by Derek Schmidt

16 Responses to “How to add Affiliate Links to Woocommerce Variations”

  1. John

    Thank you so much for this! It’s exactly what I was looking for. For some reason, my buttons are all out of order. Is it possibly to have it use the dropdown box like asked above? Here’s a link to a page using the tutorial: http://infeststation.com/product/basket-case/ . Also, since I’m linking straight to Amazon, I wish there was a way to do something about the price. Since they fluctuate, I have it all set to 0. Is there a way to get it to just not show a price? Thanks in advance!

    Reply
  2. Andew

    Derek,

    This is a GREAT article, thank you so much for putting this together!

    I’m in the same boat as Jen and Johan, is there a way to edit the code to use the existing drop-downs instead for creating buy now button for each product?

    I look forward to hear back from you!

    Thank you,
    Andrew

    Reply
  3. Dave K.

    Hi there Derek,

    I am playing around with a test affiliate site and came across your solution, really helpful!

    I was wondering if you had a quick solution for displaying the attribute name in a more readable format,

    For example, “Dark Blue”, “Neon Yellow”, and “Light Green”, as opposed to “dark-blue”, “neon-yellow” and “light-green”.

    Thanks again for the code!

    Reply

Leave a Reply

Please Note: We do our best to reply to all comments within a timely manner. However sometimes we can get pretty busy and this may delay our response a bit. If you need immediate assistance with a technical question, you may want to also try using Wordpress Forums or Stack Overflow.