WordPress User Role Permissions For Custom Post Type

Your function looks generally correct, but there are a couple of small mistakes that need to be addressed. Here’s a corrected version of your code:

function control_dfwp($query) {
    $user = wp_get_current_user();

    if (in_array('Registered for Portal', $user->roles)) {
        $query->set('author', $user->ID); // Use $user->ID instead of $current_user->ID
    }
}

add_action('pre_get_posts', 'control_dfwp');

Here are the corrections:

  1. Use $query instead of $wp_query. The parameter passed to the pre_get_posts action is already a query object, so you don’t need to use $wp_query->set().

  2. Use $user->ID instead of $current_user->ID. The correct variable to use here is $user, as defined in wp_get_current_user().

Additionally, ensure that this code is placed in your theme’s functions.php file or a custom plugin file.

This function hooks into the pre_get_posts action, which allows you to modify the query before it is executed. With this code, if a user with the role “Registered for Portal” is logged in, the query will be modified to only show posts authored by that user.

Remember to test this thoroughly to make sure it behaves as expected and doesn’t interfere with other aspects of your site.

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)