Commonly Used Custom Code Snippets
A collection of ready-to-use code snippets for extending User Registration plugin functionality beyond default settings, including examples for assigning multiple user roles during registration.
Last updated on Jul 15, 2026
Here, you will find some custom code snippets for various functions that you won't get in the available plugin settings. This list will keep on updating as we move forward.
Want to know how to add these custom code snippets to your site? Follow the step-by-step guide here: How to Add the Custom Code Snippet on Your Site
User Roles
Give Multiple User Roles
As the name suggests, this code assigns two roles to a user upon registration — in this example, Administrator and Editor. You can add or remove roles from the array as per your need.
Replace 40 in array( 40 ) with your actual form ID.
add_filter( 'user_registration_after_register_user_action', 'ur_add_user_role', 10, 3 );
function ur_add_user_role( $form_data, $form_id, $user_id ) {
if ( in_array( $form_id, array( 40 ), true ) ) {
$user = new WP_User( $user_id );
$new_role = array( 'administrator', 'editor' ); // New roles to assign to user.
foreach ( $new_role as $role ) {
$user->add_role( $role );
}
}
}You can find the form ID in the URL when editing your registration form in the WordPress dashboard.
How to add this snippet → How to Add the Custom Code Snippet on Your Site
Username Validations
Use the Entered Email as the Username
This code will automatically set the user's email address as their username during registration.
add_filter( 'user_registration_before_insert_user', 'ur_insert_username', 10, 3 );
function ur_insert_username( $user_data, $valid_form_data, $form_id ) {
$user_data['user_login'] = $valid_form_data['user_email']->value;
return $user_data;
}
add_filter( 'user_registration_before_register_user_filter', 'ur_set_email_as_username', 10, 2 );
function ur_set_email_as_username( $valid_form_data, $form_id ) {
$valid_form_data['user_login'] = $valid_form_data['user_email'];
return $valid_form_data;
}How to add this snippet → How to Add the Custom Code Snippet on Your Site
Use First Name and Last Name as the Username
This code concatenates the user's first and last name (separated by a hyphen) and uses it as the username. If the combined name already exists, the user's ID is appended to make it unique.
add_action( 'user_registration_after_register_user_action', 'ur_insert_username', 1, 3 );
function ur_insert_username( $valid_form_data, $form_id, $user_id ) {
global $wpdb;
$firstname = isset( $valid_form_data['first_name'] ) ? $valid_form_data['first_name']->value : '';
$lastname = isset( $valid_form_data['last_name'] ) ? $valid_form_data['last_name']->value : '';
$custom_username = $firstname . '-' . $lastname;
$user = get_user_by( 'login', $custom_username );
if ( ! empty( $user ) ) {
$custom_username = $custom_username . '-' . $user_id;
}
$wpdb->update(
$wpdb->users,
[ 'user_login' => $custom_username ],
[ 'ID' => $user_id ]
);
}This code requires your registration form to include both the First Name and Last Name fields.
How to add this snippet → How to Add the Custom Code Snippet on Your Site
Validation Messages
Customize the "Email Already Exists" Message
This code replaces the default "Email already exists." error message with a custom message of your choice. Replace Your Error Message goes here. with your own text.
add_filter( 'user_registration_validate_user_email_message', 'user_registration_user_email_error_message', 11, 1 );
function user_registration_user_email_error_message( $msg ) {
if ( ! empty( $msg ) && isset( $msg['user_email'] ) ) {
if ( 'Email already exists.' === $msg['user_email'] ) {
$msg['user_email'] = __( 'Your Error Message goes here.', 'user-registration' );
}
}
return $msg;
}How to add this snippet → How to Add the Custom Code Snippet on Your Site
Remove the Email Suggestion ("Did You Mean…?")
When a user enters an email address, the plugin may show a "Did you mean @example.com?" suggestion. Use the code below to disable this suggestion entirely.
add_filter( 'user_registration_mailcheck_enabled', 'false' );
function false() {
return false;
}How to add this snippet → How to Add the Custom Code Snippet on Your Site
Change the Error Message on the Lost Password Form
This code replaces the default "Invalid username or email." error message on the Lost Password form with your own custom message. Replace your custom message with the text you want to display.
add_filter( 'user_registration_add_error', function( $message ) {
if ( 'Invalid username or email.' === $message ) {
$message = __( 'your custom message', 'user-registration' );
}
return $message;
});How to add this snippet → How to Add the Custom Code Snippet on Your Site
Change the Lost Password Form Description
Use this code to replace the default description text shown above the Lost Password form. Replace Enter text with your desired message.
add_filter( 'user_registration_lost_password_message', function( $msg ) {
$msg = __( 'Enter text', 'user_registration' );
return $msg;
});How to add this snippet → How to Add the Custom Code Snippet on Your Site
Redirection Specifics
Redirect to a Different Page After Email Confirmation
By default, users are auto-logged in after clicking the email confirmation link. This code disables the automatic login and instead redirects the user to a URL of your choice. Replace the value of $url with your desired destination URL.
add_filter( 'user_registration_allow_automatic_user_login_email_confirmation', function( $allow ) {
return false;
});
add_action( 'user_registration_check_token_complete', 'ur_auto_login_email_verification', 10, 2 );
function ur_auto_login_email_verification( $user_id, $user_reg_successful ) {
if ( $user_reg_successful === true ) {
wp_set_auth_cookie( $user_id );
$url = 'https://google.com'; // Replace with your desired URL.
wp_redirect( $url );
exit;
}
}How to add this snippet → How to Add the Custom Code Snippet on Your Site
Redirect to Homepage After Social Login
Use this code to send users to your site's homepage after they log in using a social login option (such as Google or Facebook).
add_filter( 'user_registration_social_connect_login_redirect', 'user_registration_redirect_after_social_login' );
function user_registration_redirect_after_social_login( $redirect_url ) {
$redirect_url = home_url();
return $redirect_url;
}This requires the Social Connect addon to be installed and active.
How to add this snippet → How to Add the Custom Code Snippet on Your Site
Redirect Back to the Previous Page After Registration
This code redirects users back to the page they were on before they visited the registration form, once their registration is complete.
add_filter( 'user_registration_form_redirect_url', 'ur_redirect_back_original_referer', 10, 2 );
function ur_redirect_back_original_referer( $redirect_url, $form_id ) {
if ( isset( $_SERVER['HTTP_REFERER'] ) ) {
$redirect_previous_url = $_SERVER['HTTP_REFERER'];
return $redirect_previous_url;
}
return $redirect_url;
}How to add this snippet → How to Add the Custom Code Snippet on Your Site
Disable Redirection on Auto-Login
If you have set No Redirection on the registration form but have Auto-Login enabled in the login options, users will still be redirected to the My Account page after registering. Use this code to stop that behaviour and keep users on the same page.
add_filter( 'user_registration_auto_login_redirection', function( $redirect_url ) {
$redirect_url = '';
return $redirect_url;
});How to add this snippet → How to Add the Custom Code Snippet on Your Site
WooCommerce Specifics
Populate First Name and Last Name from WooCommerce Billing Fields
If your registration form includes WooCommerce Billing First Name and Billing Last Name fields, this code automatically copies those values into the user's WordPress profile First Name and Last Name fields upon registration.
add_action( 'user_registration_after_register_user_action', 'ur_update_first_last_name', 10, 3 );
function ur_update_first_last_name( $valid_form_data, $form_id, $user_id ) {
$first_name = '';
$last_name = '';
if ( isset( $valid_form_data['billing_first_name'] ) && ! empty( $valid_form_data['billing_first_name']->value ) ) {
$first_name = $valid_form_data['billing_first_name']->value;
}
if ( isset( $valid_form_data['billing_last_name'] ) && ! empty( $valid_form_data['billing_last_name']->value ) ) {
$last_name = $valid_form_data['billing_last_name']->value;
}
if ( ! empty( $first_name ) || ! empty( $last_name ) ) {
$user_data = array(
'ID' => $user_id,
'first_name' => $first_name,
'last_name' => $last_name,
);
wp_update_user( $user_data );
}
}How to add this snippet → How to Add the Custom Code Snippet on Your Site
Populate WooCommerce Billing Fields from First Name and Last Name
If your registration form includes First Name and Last Name fields, this code copies those values into the WooCommerce Billing First Name and Billing Last Name user meta fields upon registration.
add_action( 'user_registration_after_register_user_action', 'ur_update_first_last_name', 10, 3 );
function ur_update_first_last_name( $valid_form_data, $form_id, $user_id ) {
$first_name = '';
$last_name = '';
if ( isset( $valid_form_data['first_name'] ) && ! empty( $valid_form_data['first_name']->value ) ) {
$first_name = $valid_form_data['first_name']->value;
}
if ( isset( $valid_form_data['last_name'] ) && ! empty( $valid_form_data['last_name']->value ) ) {
$last_name = $valid_form_data['last_name']->value;
}
if ( ! empty( $first_name ) ) {
update_user_meta( $user_id, 'billing_first_name', $first_name );
}
if ( ! empty( $last_name ) ) {
update_user_meta( $user_id, 'billing_last_name', $last_name );
}
}How to add this snippet → How to Add the Custom Code Snippet on Your Site
Show Custom Form Field Data in WooCommerce Order Details Email
This code adds a custom registration field value to the WooCommerce Order Details email. Replace user_registration_check_box_1681727778 with the actual field name (meta key) of the field you want to display.
add_action( 'woocommerce_email_order_details', 'add_to_order_email', 10, 4 );
function add_to_order_email( $order, $sent_to_admin, $plain_text, $email ) {
$customer_id = $order->data['customer_id'];
$field_value = get_user_meta( $customer_id, 'user_registration_check_box_1681727778' );
$field_value = is_array( $field_value ) ? implode( ', ', $field_value ) : $field_value;
echo 'This is extra details.';
echo 'Field Label = ' . $field_value;
}Make sure you have synced your User Registration & Membership form with the WooCommerce checkout form. Learn more about WooCommerce integration.
How to add this snippet → How to Add the Custom Code Snippet on Your Site
Fields Specifics
Limit Username Character Length
This code limits the username field to a maximum of 15 characters. If the entered username exceeds this limit, the user will see a validation error. You can change 15 to any number you prefer.
add_action( 'user_registration_validate_user_login', 'ur_validate_user_login_field', 10, 4 );
function ur_validate_user_login_field( $single_form_field, $data, $filter_hook, $form_id ) {
$field_label = isset( $data->label ) ? $data->label : '';
$username = isset( $data->value ) ? $data->value : '';
if ( 15 < strlen( $username ) ) {
add_filter(
$filter_hook,
function ( $msg ) use ( $field_label ) {
return __( $field_label . ' cannot exceed 15 characters.', 'user-registration' );
}
);
}
}How to add this snippet → How to Add the Custom Code Snippet on Your Site
Limit Number Field Length
This code validates a Number field and requires the value to be exactly 5 digits. Replace number_box_1690949145 with the actual field name of your Number field, and adjust the regex pattern and error message as needed.
add_action( 'user_registration_validate_number', 'ur_validate_number_field', 10, 4 );
function ur_validate_number_field( $single_form_field, $data, $filter_hook, $form_id ) {
$field_label = isset( $data->label ) ? $data->label : '';
$value = isset( $data->value ) ? $data->value : '';
if ( 'number_box_1690949145' === $single_form_field->general_setting->field_name ) {
if ( ! preg_match( '/^\d{5}$/', $value ) ) {
add_filter( $filter_hook, function ( $msg ) use ( $field_label ) {
return __( $field_label . ' needs to be exactly 5 digits.', 'user-registration' );
});
}
}
}Note: To find the field name of your Number field, go to User Registration & Membership → Registration Forms, open the form, click the Number field, and check the Field Name under Advanced Settings.
How to add this snippet → How to Add the Custom Code Snippet on Your Site
Remove Spaces from the Username Field
This code prevents users from entering a username that contains spaces or whitespace characters. If a space is detected, the username will be marked as invalid.
add_filter( 'validate_username', 'custom_validate_username', 10, 2 );
function custom_validate_username( $valid, $username ) {
if ( preg_match( '/\s/', $username ) ) {
return false;
}
return $valid;
}How to add this snippet → How to Add the Custom Code Snippet on Your Site
Display Only Specific Countries in the Country Dropdown
This code limits the Country dropdown field to show only specific countries. The example below shows only Sweden and Denmark. You can replace or add country codes and names as needed.
add_filter( 'user_registration_countries_list', 'display_specific_only' );
function display_specific_only( $country_list ) {
$country_list = array(
'' => '--Select--',
'SE' => __( 'Sweden', 'user-registration' ),
'DK' => __( 'Denmark', 'user-registration' ),
);
return $country_list;
}For the WooCommerce Billing Country Field
If you are using the WooCommerce Billing Country field instead of the standard Country field, use this code instead:
add_filter( 'user_registration_billing_country_frontend_form_data', 'display_specific_country', 11 );
function display_specific_country( $data ) {
$data['form_data']['options'] = array(
'' => '--Select--',
'AU' => __( 'Australia', 'user-registration' ),
);
return $data;
}How to add this snippet → How to Add the Custom Code Snippet on Your Site
Add a New File Type to the File Upload Field
By default, the File Upload field supports a set of common file types. Use this code to add custom file types that are not available in the default settings. The example below adds CSV and XLS support.
add_filter( 'user_registration_file_upload_valid_file_type', 'urfu_add_new_valid_file_type', 10, 1 );
function urfu_add_new_valid_file_type( $validTypes ) {
$newTypes = array(
'text/csv' => __( 'CSV', 'user-registration-file-upload' ),
'application/vnd.ms-excel' => __( 'XLS', 'user-registration-file-upload' ),
);
$validTypes = array_merge( $validTypes, $newTypes );
return $validTypes;
}You need to use the MIME type of the file, not just the file extension. Visit this resource to look up MIME types for various file formats.
How to add this snippet → How to Add the Custom Code Snippet on Your Site
Misc
Change the Password Changed Email Content
The password changed email content is hardcoded into the plugin. Use the code below to customize the subject line and body of this email. Replace Your Website Name with your actual site name.
function custom_password_change_email( $pass_change_mail, $user ) {
$pass_change_mail['subject'] = 'Your Password has been changed';
$pass_change_mail['message'] = 'Hi ' . $user->display_name . ",\n\n";
$pass_change_mail['message'] .= "Your password has been changed successfully.\n\n";
$pass_change_mail['message'] .= "If you did not change your password, please contact us immediately.\n\n";
$pass_change_mail['message'] .= "Regards,\n";
$pass_change_mail['message'] .= 'Your Website Name';
return $pass_change_mail;
}
add_filter( 'password_change_email', 'custom_password_change_email', 10, 2 );How to add this snippet → How to Add the Custom Code Snippet on Your Site
Show "Log In" When Logged Out and "My Account" When Logged In on the Primary Menu
This code dynamically changes the label of a menu item based on whether the user is logged in or out. Replace the $login_url value with your actual login page URL.
function ur_login_menu_hide( $items ) {
$login_url = 'http://yoursite.com/login/'; // Your login page URL.
if ( is_user_logged_in() ) {
if ( is_array( $items ) ) {
foreach ( $items as $key => $item ) {
if ( $login_url === $item->url ) {
$items[ $key ]->title = 'Profile';
}
}
}
}
return $items;
}
add_filter( 'wp_nav_menu_objects', 'ur_login_menu_hide', 10 );How to add this snippet → How to Add the Custom Code Snippet on Your Site
Show the Username Instead of "My Account" in the Menu
Similar to the snippet above, this code replaces the menu item label with the currently logged-in user's username. Replace the $login_url value with your actual login page URL.
function ur_login_menu_hide( $items ) {
$login_url = 'http://yoursite.com/login/'; // Your login page URL.
if ( is_user_logged_in() ) {
$current_user = wp_get_current_user();
$username = $current_user->user_login;
if ( is_array( $items ) ) {
foreach ( $items as $key => $item ) {
if ( $login_url === $item->url ) {
$items[ $key ]->title = $username;
}
}
}
}
return $items;
}
add_filter( 'wp_nav_menu_objects', 'ur_login_menu_hide', 10 );How to add this snippet → How to Add the Custom Code Snippet on Your Site
Remove the user_registration_ Prefix from Custom Field Meta Keys
By default, custom field values are stored in the database with a user_registration_ prefix in the meta key. This code also saves the same values without the prefix, making them accessible to other plugins that don't use the prefixed key.
add_action( 'user_registration_after_register_user_action', 'create_user_type_meta', 10, 3 );
function create_user_type_meta( $form_data, $form_id, $user_id ) {
foreach ( $form_data as $key => $value ) {
$user_type = isset( $form_data[ $key ] ) ? $form_data[ $key ]->value : '';
update_user_meta( $user_id, $key, $user_type );
}
}How to add this snippet → How to Add the Custom Code Snippet on Your Site
Send Data to an External URL via Webhook When Profile Details Are Updated
This code sends the user's profile data to an external URL whenever they update their profile. It integrates with the Post Submission feature in User Registration & Membership Pro.
add_action( 'user_registration_save_profile_details', 'ur_post_submission_after_profile_update', 10, 2 );
function ur_post_submission_after_profile_update( $user_id, $form_id ) {
$profile = user_registration_form_data( $user_id, $form_id );
$valid_form_data = ur_get_valid_form_data( $profile );
$fields_to_exclude = ur_exclude_fields_in_post_submssion();
foreach ( $fields_to_exclude as $key => $value ) {
if ( isset( $valid_form_data[ $value ] ) ) {
unset( $valid_form_data[ $value ] );
}
}
if ( null !== get_option( 'user_registration_pro_general_post_submission_settings' ) ) {
$url = get_option( 'user_registration_pro_general_post_submission_settings' );
$single_field = array();
foreach ( $valid_form_data as $data ) {
$single_field[ $data->field_name ] = isset( $data->value ) ? $data->value : '';
}
if ( 'post_json' === get_option( 'user_registration_pro_general_setting_post_submission', array() ) ) {
$headers = array( 'Content-Type' => 'application/json; charset=utf-8' );
wp_remote_post( $url, array( 'body' => json_encode( $single_field ), 'headers' => $headers ) );
} elseif ( 'get' === get_option( 'user_registration_pro_general_setting_post_submission', array() ) ) {
$url = $url . '?' . http_build_query( $single_field );
wp_remote_get( $url );
} else {
wp_remote_post( $url, array( 'body' => $single_field ) );
}
}
}
function ur_get_profile_update_post_data() {
$single_field = array();
if ( ur_string_to_bool( get_option( 'user_registration_ajax_form_submission_on_edit_profile', false ) ) ) {
$form_data = isset( $_POST['form_data'] ) ? json_decode( stripslashes( $_POST['form_data'] ) ) : array();
foreach ( $form_data as $data ) {
$single_field[ $data->field_name ] = isset( $data->value ) ? $data->value : '';
}
} else {
$single_field = $_POST;
}
return $single_field;
}
function ur_get_valid_form_data( $profile ) {
$single_field = ur_get_profile_update_post_data();
$valid_form_data = array();
foreach ( $single_field as $post_key => $post_data ) {
$pos = strpos( $post_key, 'user_registration_' );
if ( false !== $pos ) {
$new_string = substr_replace( $post_key, '', $pos, strlen( 'user_registration_' ) );
} else {
$new_string = $post_key;
}
if ( ! empty( $new_string ) ) {
$tmp_array = ur_get_valid_form_data_format( $new_string, $post_key, $profile, $post_data );
$valid_form_data = array_merge( $valid_form_data, $tmp_array );
}
}
return $valid_form_data;
}This requires User Registration & Membership Pro. The Post Submission feature must be configured and active for this code to work.
How to add this snippet → How to Add the Custom Code Snippet on Your Site
Customize the Passwordless Login Email Content
If you use the Passwordless Login (Magic Link) feature, this code lets you customize the email message sent to users. Replace the message text inside the sprintf() call with your own content.
function modify_passwordless_login_message( $message, $email, $magic_link_url ) {
$message = sprintf(
__(
'Hello %1$s,You have requested to log in to your account without a password.Click the following link to log in: %3$sIf you did not request this login, please ignore this email.Customized Message Text Goes HereThank you,%4$s',
'user-registration-pro'
),
esc_html( $email ),
esc_url( $magic_link_url ),
esc_html( $magic_link_url ),
esc_html( get_bloginfo( 'name' ) )
);
return $message;
}
add_filter( 'ur_magic_login_link_email_message', 'modify_passwordless_login_message', 10, 3 );This requires the Passwordless Login feature available in User Registration & Membership Pro.
How to add this snippet → How to Add the Custom Code Snippet on Your Site
Extend the WordPress Login Session
By default, WordPress login sessions expire after a set period. This code extends the session duration to 3 months. You can change the value in seconds to suit your needs.
function extend_user_session() {
if ( is_user_logged_in() ) {
$session_expiration = 3 30 24 60 60; // 3 months in seconds.
setcookie( 'wordpress_logged_in', $_COOKIE['wordpress_logged_in'], time() + $session_expiration, '/' );
setcookie( 'wordpress_sec', $_COOKIE['wordpress_sec'], time() + $session_expiration, '/' );
}
}
add_action( 'init', 'extend_user_session' );How to add this snippet → How to Add the Custom Code Snippet on Your Site
Auto-Login After Email Confirmation
This code automatically logs in the user and redirects them to the page they confirmed their email on, as soon as the email confirmation token is verified.
add_action(
'user_registration_check_token_complete',
'ur_auto_login_after_email_confirmation',
10,
2
);
function ur_auto_login_after_email_confirmation( $user_id, $user_reg_successful ) {
global $wp;
if ( ! $user_id ) {
return;
}
if ( ur_string_to_bool( $user_reg_successful ) ) {
wp_clear_auth_cookie();
wp_set_auth_cookie( $user_id );
wp_safe_redirect( home_url( add_query_arg( array(), $wp->request ) ) );
}
}How to add this snippet → How to Add the Custom Code Snippet on Your Site
Add a Currency for Missing Countries
If your country's currency is not listed in the payment settings, you can add it using this code. The example below adds the Georgian Lari (GEL). Replace the currency details with the currency you need.
add_filter( 'user_registration_payments_currencies', 'ur_support_gel_currencies' );
function ur_support_gel_currencies( $currencies ) {
$extra_currencies = array(
'GEL' => array(
'name' => esc_html__( 'Georgian Lari', 'user-registration' ),
'symbol' => '₾',
'symbol_pos' => 'left',
'thousands_separator' => ',',
'decimal_separator' => '.',
'decimals' => 2,
),
);
$currencies = array_merge( $currencies, $extra_currencies );
return $currencies;
}How to add this snippet → How to Add the Custom Code Snippet on Your Site
Customize the "You Are Currently Logged In" Message
When a logged-in user visits the login page, a message is displayed informing them they are already logged in. Use this code to replace the default message with your own text.
add_filter( 'user_registration_logged_in_message', 'user_registration_logged_in_message_change', 10, 1 );
function user_registration_logged_in_message_change( $message ) {
return sprintf(
__( 'You are already logged in. Please click on log out and refresh this page again.', 'user-registration' ),
ur_logout_url()
);
}How to add this snippet → How to Add the Custom Code Snippet on Your Site
Retrieve and Display User Data and Custom Field Meta
This code retrieves and outputs the current user's basic account information along with any custom field values stored by User Registration & Membership (fields prefixed with user_registration_). It is useful for debugging or building custom profile displays.
$user_id = get_current_user_id();
if ( $user_id > 0 ) {
$user_data = get_userdata( $user_id );
if ( isset( $user_data->data ) ) {
$user_data = $user_data->data;
echo 'User ID: ' . $user_data->ID . '';
echo 'User Login: ' . $user_data->user_login . '';
echo 'User Email: ' . $user_data->user_email . '';
$meta_prefix = 'user_registration_';
$user_meta = get_user_meta( $user_id );
foreach ( $user_meta as $meta_key => $meta_value ) {
if ( strpos( $meta_key, $meta_prefix ) === 0 ) {
echo $meta_key . ': ' . implode( ', ', $meta_value ) . '';
}
}
}
}How to add this snippet → How to Add the Custom Code Snippet on Your Site
Customize the Incorrect Password Error Message
This code replaces the default WordPress login error that references the specific username when a wrong password is entered, with a more generic and secure message.
add_filter( 'login_errors', function( $msg ) {
if ( strpos( $msg, 'ERROR:The password you entered for ' ) !== false ) {
$msg = __( 'Either the username or password is incorrect.', 'user-registration' );
}
return $msg;
}, 10, 1 );How to add this snippet → How to Add the Custom Code Snippet on Your Site
Restrict Files with Content Restriction
This feature is applicable only if you have installed and activated the Content Restriction addon.
The Content Restriction addon can restrict access to pages and posts, but by default it does not protect files in your media uploads folder (such as images or PDFs). This section explains how to set up file-level restriction using a custom PHP file and server configuration.
Step 1: Create the Authorization File
In the root directory of your WordPress installation (the same folder where wp-config.php is located), create a new file named authorize.php and add the following code:
<?php
/**
* Authorization file for User Registration & Membership file restriction.
*/
define( 'WP_USE_THEMES', true );
require __DIR__ . '/wp-load.php';
$file = $_SERVER['DOCUMENT_ROOT'] . $_SERVER['REQUEST_URI'];
$uploads_folder = $_SERVER['DOCUMENT_ROOT'] . '/wp-content/uploads/';
if ( strpos( $file, $uploads_folder ) === 0 ) {
if ( ! is_plugin_active( 'user-registration-pro/user-registration.php' ) || ! file_exists( $file ) ) {
if ( file_exists( $file ) ) {
$fp = fopen( $file, 'r' );
header( 'Content-type: ' . mime_content_type( $file ) );
fpassthru( $fp );
fclose( $fp );
} else {
header( 'HTTP/1.0 404 Not Found' );
}
exit;
}
$restriction_conditions = '{
"is_logout": true,
"redirect": "https://google.com",
"message": "You do not have permission to access this file."
}';
$files_to_restrict = getFilesInDirectory( wp_upload_dir()['basedir'] );
if ( function_exists( 'ur_restrict_files' ) ) {
ur_restrict_files( $file, $restriction_conditions, $files_to_restrict );
} else {
if ( file_exists( $file ) ) {
$fp = fopen( $file, 'r' );
header( 'Content-type: ' . mime_content_type( $file ) );
fpassthru( $fp );
fclose( $fp );
} else {
header( 'HTTP/1.0 404 Not Found' );
}
exit;
}
} else {
if ( file_exists( $file ) ) {
$fp = fopen( $file, 'r' );
header( 'Content-type: ' . mime_content_type( $file ) );
fpassthru( $fp );
fclose( $fp );
} else {
header( 'HTTP/1.0 404 Not Found' );
}
exit;
}
function getFilesInDirectory( $dir ) {
$files = array();
$iterator = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator( $dir, RecursiveDirectoryIterator::SKIP_DOTS )
);
foreach ( $iterator as $file ) {
if ( $file->isFile() ) {
$files[] = trim( 'uploads' . str_replace( '\\', '/', str_replace( $dir, '', $file->getPathName() ) ) );
}
}
return $files;
}Step 2: Configure the Restriction Conditions
Inside the authorize.php file, locate the $restriction_conditions variable and update it as per your requirements:
$restriction_conditions = '{
"is_logout": true,
"redirect": "https://google.com",
"message": "You do not have permission to access this file."
}';Parameter | Description |
|---|---|
| Set to |
| The URL to redirect restricted users to. Remove this parameter if you want to show a message instead. |
| The message shown to restricted users when no redirect URL is set. |
| Restrict access to specific user roles. Example: |
Step 3: Define Which Files to Restrict
Use one of the following options for the $files_to_restrict variable depending on your needs:
// Restrict a single specific file:
$files_to_restrict = array( 'uploads/2024/06/my-image.png' );
// Restrict all files inside the uploads folder:
$files_to_restrict = getFilesInDirectory( wp_upload_dir()['basedir'] );
// Restrict all files inside a specific subfolder:
$files_to_restrict = getFilesInDirectory( wp_upload_dir()['basedir'] . '/user_registration_uploads' );Step 4: Configure Your Web Server
Once the authorize.php file is in place and configured, update your server settings to route file requests through it.
Apache Server
Open your .htaccess file and add the following code after the # END WordPress line:
# Block direct access to specific files
<FilesMatch "\.(png|jpeg)$">
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} -f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .* /authorize.php [L]
</FilesMatch>To restrict additional file types beyond PNG and JPEG, add them to theFilesMatchpattern separated by|. For example:\.(png|jpeg|pdf|docx)$
Nginx Server
Add the following block to your restrictions.config file:
location ~* \.(png|jpeg)$ {
if (-f $request_filename) {
rewrite ^ /authorize.php last;
}
} To restrict additional file types, add them to the location block separated by |. For example: location ~* \.(png|jpeg|pdf|docx)$With the authorization file in place and your server configured, any request to a restricted file will now be routed through User Registration & Membership's content restriction logic — either redirecting the user or displaying your custom access denied message.
How to add this snippet → How to Add the Custom Code Snippet on Your Site