While I'm developing a website and doing some testing I would like to block access to non-admin (and eventually non-editors) to specific pages such as the woocommerce shop and related pages.
Is there a way, without using plugins, in the functions.php
to check:
$list_of_blocked_pages = [ 'shop', 'cart', 'checkout', 'etc...' ];
if ( current_page_is_in( $list_of_blocked_pages ) && !admin && !editor ) {
redirect_to_page( $url );
}
While I'm developing a website and doing some testing I would like to block access to non-admin (and eventually non-editors) to specific pages such as the woocommerce shop and related pages.
Is there a way, without using plugins, in the functions.php
to check:
$list_of_blocked_pages = [ 'shop', 'cart', 'checkout', 'etc...' ];
if ( current_page_is_in( $list_of_blocked_pages ) && !admin && !editor ) {
redirect_to_page( $url );
}
You can use template_redirect action to redirect Specific users based on your terms. This action hook executes just before WordPress determines which template page to load. It is a good hook to use if you need to do a redirect with full knowledge of the content that has been queried.
You can use is_page function to check weather the current page is in your list of pages or not.
add_action( 'template_redirect', 'redirect_to_specific_page' );
function redirect_to_specific_page() {
if ( is_page('slug') && ! is_user_logged_in() ) {
wp_redirect( 'http://www.example.dev/your-page/', 301 );
exit;
}
}
I ended up solving like this:
function block_woocommerce_pages_for_guest() {
$blocked_pages = is_woocommerce() || is_shop() || is_cart() || is_checkout() || is_account_page() || is_wc_endpoint_url();
if( !current_user_can('administrator') && !current_user_can('editor') && $blocked_pages ) {
wp_redirect('/');
exit;
}
}
add_action( 'wp', 'block_woocommerce_pages_for_guest', 8 );
This way all non-admin and non-editor will be redirected to the homepage.
hook
to use in thefunctions.php
file? Essentially I would like to know what is the right and clean way to do that. – Dim13i Commented May 1, 2018 at 12:35woocommerce
androuting
as these are key points in answering this questions? Woocommerce pages cannot be "password protected" or made "private" through the page's publishing options. This issue might have also been solved on therouting
level I guess. Your clarification could help me in being more precise and correct next time. – Dim13i Commented May 1, 2018 at 13:11