Referral codes are created automatically, such as ref1234567. You can give a customer an easier code, such as refanna, for an influencer or a printed flyer. This snippet adds an editable field to the user profile in the WordPress admin.
Changing a code breaks every link and code the customer has already shared. Friends who use the old one won’t be tracked. Only change codes before the customer starts sharing.
Add the snippet
Read Add code snippets safely first. Checked with version 4.4.12.
add_action( 'show_user_profile', 'my_raf_code_field' );
add_action( 'edit_user_profile', 'my_raf_code_field' );
function my_raf_code_field( $user ) {
if ( ! current_user_can( 'manage_woocommerce' ) ) {
return;
}
?>
<table class="form-table">
<tr>
<th><label for="my_raf_code">Referral code</label></th>
<td>
<input id="my_raf_code" name="my_raf_code" type="text" class="regular-text"
value="<?php echo esc_attr( get_user_meta( $user->ID, 'gens_referral_id', true ) ); ?>" />
<p class="description">Must start with "ref" and use only letters and numbers.</p>
</td>
</tr>
</table>
<?php
}
add_action( 'personal_options_update', 'my_raf_code_save' );
add_action( 'edit_user_profile_update', 'my_raf_code_save' );
function my_raf_code_save( $user_id ) {
if ( ! current_user_can( 'manage_woocommerce' ) || ! isset( $_POST['my_raf_code'] ) ) {
return;
}
$code = strtolower( sanitize_text_field( wp_unslash( $_POST['my_raf_code'] ) ) );
if ( $code === get_user_meta( $user_id, 'gens_referral_id', true ) ) {
return;
}
if ( ! preg_match( '/^ref[a-z0-9]{3,20}$/', $code ) ) {
return;
}
$taken = get_users( array(
'meta_key' => 'gens_referral_id',
'meta_value' => $code,
'exclude' => array( $user_id ),
'number' => 1,
'fields' => 'ID',
) );
if ( $taken ) {
return;
}
update_user_meta( $user_id, 'gens_referral_id', $code );
}
Change a code
- Go to Users and open the customer.
- Scroll to Referral code and enter the new code, for example
refanna. - Click Update User.
The code must:
- Start with
ref. Codes typed in the coupon field only work with this prefix. - Use lowercase letters and numbers only. WooCommerce turns coupon codes into lowercase, so the snippet saves lowercase too.
- Be 6 to 23 characters long, including
ref. - Not belong to another customer.
If the code breaks one of these rules, the snippet keeps the old code without showing an error.
Check it worked
Reload the user profile. Refer a friend Link should show the link with the new code. Open it in a private window and add a product to the cart: the friend discount should apply.