Redirect logged in users from a custom post type archive page if they don’t have a specific role


I have a Custom Post Type named flashcard and post of that type are listed by an archive-flashcard.php template. The bellow function force flashcard posts to be listed only for posts authors (they have a particular client role) and administrators:

function __set_all_posts_for_author( $query ) {
    if( is_post_type_archive( array( 'flashcard' ) ) &&
        is_user_logged_in() && $query->is_main_query() && !current_user_can( 'manage_options' ) 
    ) {
        $current_user = get_current_user_id();
        $query->set( 'author', $current_user );
add_action( 'pre_get_posts', '__set_all_posts_for_author' );

The described CPT have in the permalink a word privat. A second function is redirecting not logged in users, or logged in users that doesn’t have a client or an administrator role, if they try to acces a such permalink:

add_action( 'template_redirect', 'wpse_restrict_private' );
function wpse_restrict_private() {
    $user = wp_get_current_user();
    if( strpos( get_permalink(), 'privat' ) !== false ) {
        if( !$user->exists() || //if user is not logged in
            //or it is not a client or an administrator
            !array_intersect( array( 'client', 'administrator' ), $user->roles )
        ) {
            wp_redirect( site_url() ); //redirect to site URL

The problem is that when logged in users that are not clients or administrators access the flashcard archive (that have the word privat in permalink) they are not redirected and a Not found error is displayed. How can I solve this?

, , Iurie Malai 3 years 2020-08-22T15:10:20-05:00 0 Answers 39 views 0

Leave an answer