如何在用户未登录特定页面时重定向到登录页面

时间:2020-08-23 作者:Riskhan

在我的插件中有许多页面。如果用户没有在特定页面上登录,我想重定向到登录页面。我使用了下面的代码,但它重定向到所有页面的登录页面。我只想指定页面。

<?php
class Coupon {
  private static $instance = null;

  private function __construct(){
    add_action( \'init\', array(&$this, \'add_shortcodes\' ));
    add_action( \'template_redirect\', array(&$this, \'redirect_user\' ));
  }

  public static function get_instance(){
    if(!self::$instance){
      self::$instance = new Coupon();
    }
    return self::$instance;
  }

  function add_shortcodes() {
    add_shortcode( \'coupon-form\', array(&$this,\'coupon_form\' ));
  }

  function redirect_user() {
    Log::d("redirected");
    if ( ! is_user_logged_in() && ! is_page( \'login\' ) ) {
      wp_redirect( Login::url() );
      exit;
    }
  }
  
  function coupon_form() {
    ob_start();
      ?>
          <div class="coupon_widget_form">
              <form id="coupon_form" name="coupon_form" method="post" action="">
                  <div>
                      <label for="coupon">Coupon</label>
                      <input type="text" id="coupon" value="YZ7U PQnm EAQ3" size="25" name="coupon" />
                  </div>
                  <div>
                      <input type="submit" name="coupon_submit" value="Redeem"/>
                  </div>
              </form>
          </div>
      <?php
      return ob_get_clean();
  }
}
?>

1 个回复
最合适的回答,由SO网友:Sally CJ 整理而成

据我所知,你只需要改变if 在您的redirect_user() 功能到:

// List of Page slugs of the particular pages in question.
$pages = array( \'page-slug\', \'another-slug\', \'etc-etc\' );
// .. or specify a list of Page IDs: array( 1, 2, 3, ... )

// Redirect only if the current Page\'s slug (or ID) is within the above list.
if ( ! is_user_logged_in() && is_page( $pages ) ) {
    wp_redirect( Login::url() );
    exit;
}
但当然,通过;“第”页;,我猜你指的是一页,即page 类型

如果情况并非如此,即您(也)在引用其他WordPress页面,如CPT和术语档案,那么您可以查看conditional tags here 只需使用与特定页面匹配的页面(is_page() 是这些条件标记之一)。但确切的条件/逻辑肯定取决于应该应用登录重定向的页面类型。

// Example..
if ( ! is_user_logged_in() && (
    is_page( array( \'foo\', \'bar\', \'etc-slug\' ) ) || // check if it\'s one of the Pages
    is_singular( \'my-cpt\' )                         // or a if it\'s any single CPT pages
) ) {
    wp_redirect( Login::url() );
    exit;
}