Are you a GenerateCustomer?

Do you have an active GP Premium or GenerateBlocks Pro license key?

Create a GenerateSupport account for GeneratePress and GenerateBlocks support in one dedicated place.

Create an account
Already have a GenerateSupport account? Login

Just browsing?

Feel free to browse the forums. Support for our free versions is provided on WordPress.org (GeneratePress, GenerateBlocks).

Want to become a premium user? Learn more below.

Restricting elements to logged-in users with specific roles

  • I’m using the Members plugin to restrict certain pages to logged-in users with specific roles. However, I noticed that some of my GeneratePress elements on these pages are still visible to everyone.

    Is there a way to make these elements visible only to logged-in users with specific roles? If so, what would be the best approach?

  • Hi there,

    That will require a custom snippet to achieve. For example, if you want to show the Elements with IDs 123, 124, and 125 to users with the ‘subscriber’ role, the snippet would look something like this:

    function show_elements_to_subscribers( $display, $post_id ) {
        // Elements that should only be visible to subscribers
        $subscriber_elements = array( 123, 124, 125 );
        
        // Check if this is one of our subscriber-only Elements
        if ( in_array( $post_id, $subscriber_elements ) ) {
            // Only show to logged-in subscribers
            if ( is_user_logged_in() ) {
                $user = wp_get_current_user();
                
                // Check if user has the subscriber role
                if ( in_array( 'subscriber', (array) $user->roles ) ) {
                    return true;
                }
            }
            
            // Not a subscriber, don't show the Element
            return false;
        }
        
        // Return original value for other Elements
        return $display;
    }
    add_filter( 'generate_element_display', 'show_elements_to_subscribers', 10, 2 );
    

    Adding PHP: https://docs.generatepress.com/article/adding-php/

    If you have more specific conditions, let me know and I’ll help adjust the snippet accordingly.

Viewing 2 posts - 1 through 2 (of 2 total)
  • You must be logged in to reply to this topic.