Home / Archive / MemberPress: Redirect To Specific Page Based on Rule
Duplicate Snippet

Embed Snippet on Your Site

MemberPress: Redirect To Specific Page Based on Rule

This code snippet will redirect users to a custom URL if the visited post is protected by a specific rule. All posts protected with other rules will still redirect users to the general redirect URL set at Dashboard > MemberPress > Settings > Pages.

For this code snippet to work, the Redirect unauthorized visitors to a specific URL option must be enabled and set. The code snippet can’t be used for the Custom URI rule type.

The rules-specific redirections added to this code snippet must be added in order of priority. The rule with the highest precedence should be listed first.

You should replace the dummy rule ID of 123 with the ID of your rule. Also, you should replace the dummy URL with the URL of the page users should be redirected to. These changes should be made on the following lines:

if ( in_array( 123, $rule_ids ) ) {
$redirect_url = 'https://yourdomain.com/register/membership-1/';

To add the second rule-specific redirection, the following lines are used in the example code:

else if ( in_array ( 456, $rule_ids ) ) {
$redirect_url = 'https://yourdomain.com/register/membership-2/';

This code can be repeated to add additional redirections. Each of these redirections should be modified by replacing the rule ID and the redirection URL as described for the first redirection.

More information about using this code can be found here: https://memberpress.com/docs/add-rule-specific-unauthorized-redirections/

Code Preview
php
<?php
function mepr_redirect_specific_page( $redirect_url, $delim, $uri ) {
	$current_post = MeprUtils::get_current_post();
	$rules = MeprRule::get_rules( $current_post );
	
	if ( !empty( $rules ) ) {
		$rule_ids = array_column( $rules, 'ID' );
		
		if ( in_array( 123, $rule_ids ) ) {
			$redirect_url = 'https://yourdomain.com/register/membership-1/';
		} else if ( in_array ( 456, $rule_ids ) ) {
			$redirect_url = 'https://yourdomain.com/register/membership-2/';
		}
	}
	
	return $redirect_url;
}
add_filter( 'mepr-rule-redirect-unauthorized-url', 'mepr_redirect_specific_page', 999, 3 ); //Make sure this runs last

Comments

Add a Comment