我想限制对我的 woocommerce 网站上的产品的访问。 如果用户没有登录,我想将他们重定向到注册页面。 我正在使用此代码,但我的所有产品都重定向到注册页面:
function wpse_131562_redirect() {
if (! is_user_logged_in()
&& (is_woocommerce() || is_cart() || is_single(1735) || is_checkout())
) {
// feel free to customize the following line to suit your needs
wp_redirect( 'https://www.la-chaine-maconnique.fr/my-account/' );
exit;
}
}
add_action('template_redirect', 'wpse_131562_redirect');
你想到了什么?
它从所有产品重定向到注册页面的原因是,当您使用
wp_redirect
时,is_woocommerce()
函数正在使用 Woocommerce 模板的所有页面上运行。
我认为您需要的是以下内容:
function reg_redirect(){
if( is_product(1735) && !is_user_logged_in() ) {
wp_redirect( 'https://www.la-chaine-maconnique.fr/my-account/' );
exit();
}
}
add_action('template_redirect', 'reg_redirect');
您可以尝试验证操作器是否正常工作! 您可以将“&&”更改为“and”,或者只在 if 语句中添加一个条件:这意味着执行以下操作: (请注意,这将重定向所有用户,甚至是已登录的用户)
function wpse_131562_redirect() {
if ( is_single(1735)) {
// feel free t`enter code here`o customize the following line to suit your needs
wp_redirect( 'https://www.la-chaine-maconnique.fr/my-account/' );
exit;
}
}
add_action('template_redirect', 'wpse_131562_redirect');
如果上述代码仅适用于您的目标单一产品,请尝试您的操作。 更好的解决方案是避免使用 is_signle(),据报道 is_single 无法与 WooCommerce 正常工作,您可以尝试以下操作:
function wpse_131562_redirect() {
global $post;
if ($post->ID = '1735' and !is_user_logged_in()) {
// whatever you try to do here for product id = 123 will work!
wp_redirect( 'https://www.la-chaine-maconnique.fr/my-account/' );
}
}
add_action('template_redirect', 'wpse_131562_redirect');
您可以将 is_single("product id here") 用于要重定向的特定产品。您可以在编辑产品时在网址上找到您的产品 ID。
function wpse_131562_redirect() {
if (
is_user_logged_in()
&& (is_single('7121') || is_single('7118') || is_single('7117') || is_single('7116')|| is_single('7115') || is_single('7112'))
) {
// feel free to customize the following line to suit your needs
wp_safe_redirect( wc_get_page_permalink( 'myaccount' ) );
exit;
}
}
add_action('template_redirect', 'wpse_131562_redirect');