I have a custom post type Portfolio and each portfolio is a questionnaire. If I email the link of a portfolio to a client via email.

How can I expire link after 10 minutes, So if client has came after 10 minutes to visit the link Then there should be message that link has expired Please try again.

How can I do that?

3 s
3

Ok I came up with this

add_action( 'wp_loaded', 'my_create_questionnaire_link');
function my_create_questionnaire_link(){

  // this check is for demo, if you go to http://yoursite.demo/?create-my-link, you will get your unique url added to your content
  if( isset( $_GET['create-my-link'] ) ){

    // This filter is for demo purpose
    // You might want to create a button or a special page to generate your
    // unique URL
    add_filter( 'the_content', function( $content ){

      // This is the relevant part
      // This code will create a unique link containing valid period and a nonce

      $valid_period = 60 * 10; // 10 minutes
      $expiry = current_time( 'timestamp', 1 ) + $valid_period; // current_time( 'timestamp' ) for your blog local timestamp
      $url = site_url( '/path/to/your/portfolio/page' );
      $url = add_query_arg( 'valid', $expiry, $url ); // Adding the timestamp to the url with the "valid" arg
      $nonce_url = wp_nonce_url( $url, 'questionnaire_link_uid_' . $expiry, 'questionnaire' );  // Adding our nonce to the url with a unique id made from the expiry timestamp

      // End of relevant part
      // now here I return my nounce to the content of the post for demo purposed
      // You would use this code when a button is pressed or when a special page is visited

      $content .= $nonce_url;

      return $content;
    } );
  }

}

This is where you would check for the validity of the unique URL

add_action( 'template_redirect', 'my_url_check' );
function my_url_check(){

  if( isset( $_GET['questionnaire'] )){

    // if the nonce fails, redirect to homepage
    if( ! wp_verify_nonce( $_GET['questionnaire'], 'questionnaire_link_uid_' . $_GET['valid'] ) ){
      wp_safe_redirect( site_url() );
      exit;
  }

    // if timestamp is not valid, redirect to homepage
    if( $_GET['valid'] < current_time( 'timestamp', 1) ){
      wp_safe_redirect( site_url() );
      exit;
    }

    // Show your content as normal if all verification passes.
  }
}

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *