Dynamic URL Rewrite rule

If you place your if/else statement within the function you call on the init hook, the redirect will only occur if your $var evaluates to false. For example

function 290127_init_validate(){

  if ( ! is_post_type_archive('book') ) {
    return;
  }

  if ($var != null) {
   // do something
  } else {
    wp_redirect('new url');
  }
}
add_action("init", "290127_init_validate");

WordPress provides a number of conditional tags which can be used to provide even more granular control over when a function should run. You can use these conditional tags at the beginning of your function and return early if they don’t evaluate to true. The example function above will only run on ‘book’ custom post type archive page.