0

I am creating a plugin where I am checking for parameters passed in the url for a page, then using the values of those parameters to change the Title, meta tags and make some other SEO changes. But I am running into problems trying to combine actions and filters properly to make this happen. Here is a sample of some of the things I am doing. First I am registering the variable passed in the url

    add_action('init', 'register_tag');

    function register_tag() {
      add_rewrite_tag('%address%','([^&]+)');
    }

Then I am obtaining the variable from $wp_query and setting the Title amongst other things.

    add_filter('wp_head', 'seo_features');

    function seo_features() {
       global $wp_query,$post,$address;
       $address = $wp_query->query_vars['address'];
       if ($address) {
          $post->post_title = $address;
          add_filter('wp_title', set_title);
          add_filter('wpseo_title', set_title);
          remove_action('wp_head', 'rel_canonical');
       }
    }
    function set_title($title) {
       global $address;
       return $address;
    }

But I don't think you can make add_action() or add_filter() calls from within an add_filter()?

I'm not sure how to do this correctly. I have to use add_action("init") to register the tag (and also to add a related rewrite rule using add_rewrite_rule() ). But it seems I can only get the value of the variable $address from $wp_query from within an add_filter call. Trying to access it without a filter/action doesn't work as it is called too early.

Any ideas on what the correct order I should be doing this?

1

You can add or remove hooks from inside other hooks if you get the timing right but I don't understand why you are making this so complex.

function set_title($title) {
  global $wp_query,$post,$address;
  $address = $wp_query->query_vars['address'];
  if ($address) {
    return $address;
  }
}
add_filter('wp_title', 'set_title');

If you need the share the value, use a static variable:

function my_address() {
  static $address = '';
  global $wp_query;
  if (empty($address)) {
    $address = $wp_query->query_vars['address'];
  }
  return $address;
}

function set_title($title) {
  return my_address();
}
add_filter('wp_title', 'set_title');

Or wrap the whole thing in a class.

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.