1

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.

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

1 Answer 1

0

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

1
  • Thanks so much for the response, Pat. I think the issue with this solution in my case is that I am using various page templates that include the code I need to protect. Therefore everything outside of the content (but within the page template) will still be available. Commented Nov 27, 2013 at 14:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.