wpf_user_can_access

Overview

This filter is run when determining whether a user can access any content that is restricted by WP Fusion. You can use it to create your own dynamic access rules based on criteria that aren’t available through WP Fusion’s meta boxes. To use the code examples below, add them to your active theme’s functions.php file.

Parameters

  • $can_access: This variable represents whether or not the user can access the content, as determined by your existing access rules. It will either be true or false.
  • $user_id: ID of the current logged in user. Will be false if the user isn’t logged in.
  • $post_id: Post ID for the post being requested.

Examples

Deny access to posts within a certain category

The example below will allow access to posts in the category “My Category” only to users who have the tag “Special Tag”.

function restrict_post_categories( $can_access, $user_id, $post_id ) {
	
	if ( in_category( 'My Category', $post_id ) && ! wp_fusion()->user->has_tag( 'Special Tag', $user_id ) ) {
		return false;
	} else {
		return true;
	}

}

add_filter( 'wpf_user_can_access', 'restrict_post_categories', 10, 3 );

Flip access rules for a single post

The example below inverts the access rules for a single post, in this case a post with ID 1234. Instead of requiring the tags specified in the WP Fusion meta box to view the post, this code makes it so that if the user has any of those tags access will be denied.

function my_wpf_flip_access_rules( $can_access, $user_id, $post_id ) {

	// Optional: limit the rule flipping just to certain post IDs (1234 and 4567)
	if( $post_id != 1234 ) {
		return $can_access;
	}

	$post_restrictions = get_post_meta( $post_id, 'wpf-settings', true );

	if ( empty( $post_restrictions ) || empty( $post_restrictions['allow_tags'] ) ) {
		return $can_access;
	}

	$user_tags = wp_fusion()->user->get_tags( $user_id );

	$result = array_intersect( $user_tags, $post_restrictions['allow_tags'] );

	if ( empty( $result ) ) {

		// If user does *not* have any of the tags specified in the post restrictions, grant access
		return true;

	} else {

		// If user *does* have any of the tags, deny access
		return false;

	}

}

add_filter( 'wpf_user_can_access', 'my_wpf_flip_access_rules', 10, 3 );