0

I need to create a rewrite rule that only runs if an in page variable exists, here is some pseudo code of what I am tying to accomplish.

if ($var != null) {
// do something
}

else {
url_rewrite('current_url', 'new url');
}

The issue I am running into is that the WordPress built in function requires activation on init and would redirect regardless of whether or not the rule is present.

Any help is appreciated!

  • rewriting and redirection are two different, unrelated things, it's not clear what your end goal and this variable dependency is. – Milo Jan 4 '18 at 16:14
0

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.

  • 1
    I believe the init action hook occurs before the post type is determined, pre_get_posts is the recommended action hook to use since it fires after the query variable object is created, but before the actual query is run. – Gary D Jan 5 '18 at 6:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.