How to redirect to login page when user not loggedin on a particular page

Question

In my plugin there are many pages. I want to redirect to a login page if the user is not loggedin on a particular page. I used below code, but it redirect to login page on all pages. I want to specific page only.

<?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();
  }
}
?>
0
, Riskhan 3 years 2020-08-23T01:10:37-05:00 0 Answers 53 views 0

Leave an answer

Browse
Browse