How to setup wordpress custom query params with pretty url format

WordPress pages can handle query parameters in url in the traditional format of “key=value”. e.g. If you want to create a page to display details of a product, you can  create a page /detail/ and take a query parameter productid. So the url may look like /detail/?productid=1234.

To handle this productid in your page, you can write write a plugin with shortcode or filter with some code like:

$product = $_GET['productid'];
// ... code to look up and display (or modify content) product info

Custom query param and pretty url

If you want to create pretty url structure, the you can use wordpress endpoint and custom query parameters. For that you will have to write a plugin in wordpress. Here is the code for endpoint and custom query params.

function my_query_vars($vars) {
  $vars[] = "productid";
  return $vars;
}
add_filter('query_vars', 'my_query_vars');
function my_rewrite_endpoint(){
  // Use EP_PERMALINK | EP_PAGES for pages and posts both
  add_rewrite_endpoint( 'productid', EP_PAGES );
}
add_filter('init','my_rewrite_endpoint');

Pretty Url format

Now the new url structure will look like this:

/detail/productid/1234/

To read the custom query param productid, you can use the following code in you wordpress plugin:

$productid = get_query_var('productid')
// ... code to lookup and display (or modify content) product info

Canonical url

You may also want to consider removing canonical url for such pages if there are any. I’m using WordPress SEO plugin which also adds canonical url to all pages. Here is code snipped to remove canonical url for a page:

function my_wpseo_canonical ($canonical) {
  if (preg_match('#/detail/#i', $canonical)) {
    return false;
  }
  return $canonical;
}
add_filter( 'wpseo_canonical', 'my_wpseo_canonical');
Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments