WordPress hook to authenticate user for pre-defined URLs

I’m building a fairly complex project that has many frontend editing pages. For example, add/edit/list custom post types, edit profile, and so on, all from the frontend.

At the moment I can of course check if user is logged in on each frontend login-walled page. However, this seems like a bad way of solving this problem as I’ll have the same conditional on many pages and thus lots of repeated code.

Read More

I was thinking perhaps there is a better way where I could authenticate based on some hook (that I can’t finds). I hoped I could do something like:

# create array of URLs where login is required
$needLoginArr = array(url1, url2, url3, ...)

# If current requested URL is in above array, then redirect or show different view based on whether or not user is logged in

It might not be practical in future to have conditional on each page as I plan on integrating within different plugins, so would be useful to use URL to authenticate.

I’m probably missing something here so if there’s a better way please let me know.

Thanks

Related posts

Leave a Reply

1 comment

  1. You could add your list of page IDs into an option:

    $need_login = array(
        'page1',
        'page1/subpage',
        'page2',
        // and so forth
    );
    $need_login_ids = array();
    foreach( $need_login as $p ) {
        $pg = get_page_by_path( $p );
        $need_login_ids[] = $pg->ID;
    }
    update_option( 'xyz_need_login', $need_login_ids );
    

    Then, to check if your page is in the $need_login group:

    add_filter( 'the_content', 'so20221037_authenticate' );
    function so20221037_authenticate( $content ) {
        global $post;
        $need_login_ids = get_option( 'xyz_need_login' );
        if( is_array( $need_login_ids ) && in_array( $post->ID, $need_login_ids ) ) {
            if( is_user_logged_in() ) {
                // alter the content as needs
                $content = 'Stuff for logged-in users' . $content;
            }
        }
        return $content;
    }
    

    References