Question

I am currently using a Wordpress plugin (Pagerestrict plugin which references URLS based on Page ID/Slugs)to restrict certain pages to logged in users only. This plugin works fine with standard wordpress URL structure but the issue I have is some of my pages which are directly linked to some plugin functionality have http://mywebsite.com/wp-content/plugins/purchase.php instead of a standard http://mywebsite.com/wp-content/plugins/purchase/ wordpress url structure. So what i tried in cases like this is to manually add the functionality below which didn't work

function my_page_template_redirect() {
            $url_path = preg_replace('/\?.*/', '', $_SERVER['REQUEST_URI']);
        
            if( strpos($url_path, '/wp-content/plugins/purchase.php/') !== 0 && ! is_user_logged_in() )
            {
                wp_redirect( wp_login_url() );
                die;
            }
        }
    
add_action( 'template_redirect', 'my_page_template_redirect' );

i also saw this https://wpexplorer-themes.com/total/snippets/restrict-content-access-user/ article which recommended something similar to what i was looking for but the only twist here is it matches page conditions with $page_id instead of the URL and since my URL (refer above) which is directly linked to plugin page is not generated via wp pages or posts it has no IDs or slugs. Is there a way to workaround this? Will appreciate some recommendations.

Was it helpful?

Solution

The template redirect is most useful for managing the output of theme files. To redirect a non-logged in user when the page loads, attach your function to the 'init' hook. (If you call it sooner than that in the stack, you may get an error because the function definition hasn't been included yet.)

In short, if you replace the action hook in the code you provided with:

add_action( 'init', 'my_page_template_redirect' );

it should achieve what you're trying to accomplish.

Reference: https://developer.wordpress.org/reference/functions/is_user_logged_in/

Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top