Determine WP_Query parameters from URL

Edited Jul, 07 2014 at 6:28


There are a lot of gotchas with your approach. It will not work if there are any custom rewrite rule, it (probably) will not work if server is IIS and pretty permalink are active, it will not work for custom post types, it will not work for archive or search urls and so on.

To obtain a sing post/page url from a url in a affordable way, there is the function url_to_postid, e.g.

$id = url_to_postid( $query_url['path'] );

if ( is_numeric( $id ) && (int) $id > 0 ) {
  // the required post id is: $id
} else {
  // the url is not for a single post, may be an archive url, a search url or even
  // a non-valid 404 url
}

If you are interested only is single post (even CPT) or page urls, then probably the few lines above are the only thing you need, but if you need to parse all kind of WordPress urls, then you need something else, and is not something really easy.

The only way to obtain query vars from a url in an affordable way, is to reproduce the way WordPress uses to parse an url.

That is done in core by the method parse_request of the WP class.

However, using that method for our purpose explained above is hard/discouraged because:

  • it directly accesses to $_SERVER, $_POST and $_GET variables, making hard to parse arbitrary urls not related with current HTTP request
  • it triggers some action hooks strictly related to current HTTP request parsing, that makes no sense to trigger for arbitrary urls
  • it accesses and modifies properties of global $wp variable that should not be changed after request is parsed or very likely things will break.

What we can do is starting from the code there, remove the parts we don’t need, and make the code use an arbitrary url instead of the one from current HTTP request.

Core parse_request method is 214 lines long (v. 3.9.1) and do that work can be such a pain, but luckily someone has already done the hard work, see here.