A child shoe asked how to realize that non logged in users can only browse specified classified articles. Here is the method.
Only visitors are allowed to browse articles of the specified category
Similar codes can be found online:
//The template_redirect action hook is bound to be executed, so this hook is valid for the whole station add_action( 'template_redirect', 'ashuwp_show_only_login', 0 ); function ashuwp_show_only_login(){ //Judge the login, and the about page is allowed to access if( ! is_page('about') && ! is_user_logged_in() ){ auth_redirect(); // Jump to login page exit(); } }
Code source: www.ashuwp.com
The original code only allows non login users to visit the specified page or directly jump to login.
Make a simple change and add a judgment in_category
, only archive pages and articles of the specified category are allowed to be accessed.
//Home page and designated classified articles can be accessed add_action( 'template_redirect', 'ashuwp_show_only_login', 0 ); function ashuwp_show_only_login(){ //Judge the login. Only classified articles with ID 3 and 2 are allowed to be accessed if( ! in_category( array( 3,2 ) ) && ! is_home() && ! is_user_logged_in() ){ auth_redirect(); // Jump to login page exit(); } }
By default, non login users are only allowed to visit the homepage of the website and classified archive pages and articles with classified IDs 3 and 2. Otherwise, they will jump to the login page.
hold ! in_category The exclamation mark in front is removed and changed to in_category On the contrary, access to classified articles with classification IDs 3 and 2 will jump to login, and other articles can be accessed normally.
The code is added to the topic function template functions.php.
Most of the articles on this site are original and used for personal learning records, which may be helpful to you, for reference only!