This code snippet will show you how to populate a form’s hidden field with the ID of the currently tracked affiliate. The affiliate ID is retrieved from AffiliateWP’s affwp_ref cookie, stored in a variable, and then added to the hidden input.

The snippet below inserts the JavaScript into the page using WordPress’ wp_footer action hook for example purposes only. Feel free to move the code to wherever you need it.

<?php

/**
 * Populates a hidden input field with the currently tracked Affiliate's ID.
 * 
 * @link https://andrew.dev/snippets/populate-a-hidden-field-with-the-affiliates-id/
 */
function am_affwp_populate_hidden_field_with_affiliate_id() {
	?>
	<script>
		jQuery(document).ready(function() {
			// Retrieve the affiliate ID from the affwp_ref cookie.
			var affiliateId = Cookies.get( 'affwp_ref' );

			// Populate the hidden field with the AffiliateWP.
			jQuery('#your-hidden-input-field').val( affiliateId );
		});
	</script>
	<?php
}
add_action( 'wp_footer', 'am_affwp_populate_hidden_field_with_affiliate_id' );

Why this snippet may be useful

You have a form on your site that stores form entries in the WordPress admin. This would allow you to store the ID of the affiliate who referred the site visitor.

Leave a Reply

Your email address will not be published. Required fields are marked *