Redirecting Based on User ID(s) in Post Meta

This Pro tutorial provides the steps to redirect single post pages to a specific URL/location like the site’s homepage if the user viewing the page is not the one set as the value of a custom field for that post.

Sample scenario:

CPT: service

Custom Field: access_user of the type User created using a plugin like ACF or Meta Box.

For a service titled say, “SEO” this custom field’s value has been set to “John Smith”.

When example.com/service/seo/ is viewed by anyone but John Smith, we shall redirect them to the homepage.

We are also going to cover the case where the custom field can contain multiple users.

Add the following in child theme‘s functions.php (w/o the opening PHP tag) or a code snippets plugin:

// Redirect singular service pages to homepage if the user ID does not match the "access_user" field value.
add_action( 'template_redirect', function() {
	// if we are not viewing a singular service CPT page, abort.
	if ( ! is_singular( 'service' ) ) {
		return;
	}
	
	// if the "access_user" custom field value does not match the current user ID, redirect to homepage.
	if ( get_post_meta( get_the_ID(), 'access_user', true ) != get_current_user_id() ) {
		wp_safe_redirect( home_url() );
		exit;
	}
} );

Note that if the strict comparison operator !== is used, it won’t work because the left operand returns a string and the right one, an integer.

If the custom field is set to support a selection of multiple users, change the code to:

// Redirect singular service pages to homepage if the user ID does not match the "access_user" field value.
add_action( 'template_redirect', function() {
	// if we are not viewing a singular service CPT page, abort.
	if ( ! is_singular( 'service' ) ) {
		return;
	}
	
	// if the current user ID is not in the array of user IDs in the "access_users" custom field, redirect to homepage.
	if ( ! in_array( get_current_user_id(), get_post_meta( get_the_ID(), 'access_users' ) ) ) {
		wp_safe_redirect( home_url() );
		exit;
	}
} );