Lego2012
12/13/2016 - 3:38 PM

Restrict access to all CPT single entries to a role

Restrict access to all CPT single entries to a role

<?php
//* Do NOT include the opening php tag shown above. Copy the code shown below.

/**
 * Checks if a particular user has a role.
 * Returns true if a match was found.
 *
 * @param string $role Role name.
 * @param int $user_id (Optional) The ID of a user. Defaults to the current user.
 * @return bool
 * Source: https://docs.appthemes.com/tutorials/wordpress-check-user-role-function/
 */
function appthemes_check_user_role( $role, $user_id = null ) {

    if ( is_numeric( $user_id ) )
        $user = get_userdata( $user_id );
    else
        $user = wp_get_current_user();

    if ( empty( $user ) )
        return false;

    return in_array( $role, (array) $user->roles );
}

add_action( 'genesis_before_entry', 'sk_access_control' );
function sk_access_control() {

    if ( ! is_singular( 'portfolio' ) ) {
        return;
    }

    // Remove the post content
    remove_action( 'genesis_entry_content', 'genesis_do_post_content' );

    if ( appthemes_check_user_role( 'client' ) ) {

        // add the post content
        add_action( 'genesis_entry_content', 'genesis_do_post_content' );
    }
}