【发布时间】:2021-04-15 23:32:37
【问题描述】:
我正在建立一个私人 WooCommerce 门户网站供客户订购。
我试图避免臃肿的会员插件,在网上找到了这段代码并且运行良好,但是如果注销的用户访问了“任何”页面而不仅仅是单个页面 ID,我希望它重定向到 url
add_action( 'template_redirect', 'redirect_if_user_not_logged_in' );
function redirect_if_user_not_logged_in() {
if ( is_page('slug || ID') && ! is_user_logged_in() ) { //example can be is_page(23) where 23 is page ID
wp_redirect( 'http://your-redirect-page-here ');
exit;// never forget this exit since its very important for the wp_redirect() to have the exit / die
}
}
我已尝试删除页面检查以及 wordpress 文档中提到的 is_page()
// When any single Page is being displayed.
is_page();
// When Page 42 (ID) is being displayed.
is_page( 42 );
// When the Page with a post_title of "Contact" is being displayed.
is_page( 'Contact' );
// When the Page with a post_name (slug) of "about-me" is being displayed.
is_page( 'about-me' );
/*
* Returns true when the Pages displayed is either post ID 42,
* or post_name "about-me", or post_title "Contact".
* Note: the array ability was added in version 2.5.
*/
is_page( array( 42, 'about-me', 'Contact' ) );
【问题讨论】:
-
您是否考虑过您在登录时正在测试它,所以不会生效?我测试了代码,它工作正常。我能想到的唯一另一件事是,有另一个优先级更高的操作首先执行某项操作,这会阻止您的函数运行。
-
我正在另一个浏览器上测试(注销)代码在指定页面 ID 时工作正常。但是,我正在寻找一种方式来表示“如果已注销的用户访问了任何页面,则重定向到登录自定义 URL”
-
试试这个方法: if ( !is_page( array( 123, 'login-page', 'contact-us') ) && ..... 123 将是主页 id。跨度>
标签: php wordpress redirect woocommerce