Skip to content

Instantly share code, notes, and snippets.

@Clivern
Last active August 29, 2015 14:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Clivern/2476ec77ad55248f445a to your computer and use it in GitHub Desktop.
Save Clivern/2476ec77ad55248f445a to your computer and use it in GitHub Desktop.
How To Add Custom Rewrite Rules In WordPress
<?php
/*
Plugin Name: Products Plugin
Plugin URI: http://clivern.com/how-to-add-custom-rewrite-rules-in-wordpress/
Description: Register URL rules for our products
Version: 1.0
Author: Clivern
Author URI: http://clivern.com/
License: MIT
*/
function products_plugin_rules()
{
add_rewrite_rule('store/([^/]*)/?([^/]*)/?([^/]*)', 'index.php?pagename=store&company_name=$matches[1]&company_products=$matches[2]&company_product_id=$matches[3]', 'top');
}
function products_plugin_activate()
{
products_plugin_rules();
flush_rewrite_rules();
}
function products_plugin_deactivate()
{
flush_rewrite_rules();
}
function products_plugin_query_vars($vars)
{
$vars[] = 'company_product_id';
$vars[] = 'company_products';
$vars[] = 'company_name';
return $vars;
}
//visit example.com/store/apple to show all apple products
//visit example.com/store/apple/laptops to show apple laptops
//visit example.com/store/apple/laptops/1 to show apple laptop info
function products_plugin_display()
{
$pagename = get_query_var('pagename');
$company_product_id = get_query_var('company_product_id');
$company_products = get_query_var('company_products');
$company_name = get_query_var('company_name');
if('store' == $pagename){
if ('apple' == $company_name) {
//show all products of apple or one product
var_dump($company_products);
var_dump($company_product_id);
exit;
} elseif ('sony' == $company_name) {
//show all products of sony or one product
var_dump($company_products);
var_dump($company_product_id);
exit;
}
//and so on..
}
}
//register activation function
register_activation_hook(__FILE__, 'products_plugin_activate');
//register deactivation function
register_deactivation_hook(__FILE__, 'products_plugin_deactivate');
//add rewrite rules in case another plugin flushes rules
add_action('init', 'products_plugin_rules');
//add plugin query vars (product_id) to wordpress
add_filter('query_vars', 'products_plugin_query_vars');
//register plugin custom pages display
add_filter('template_redirect', 'products_plugin_display');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment