Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save JosephNC/ed12dd934c26e80bfb33fac2298405e8 to your computer and use it in GitHub Desktop.
Save JosephNC/ed12dd934c26e80bfb33fac2298405e8 to your computer and use it in GitHub Desktop.
Some methods I generally use to create my own rewrite rules for WordPress. Taken from WordHub project.
<?php
/**
* Some basics for creating your own rewrite rules in WordPress. Taken from
* my WordHub plugin.
*/
class Whatever {
function init() {
add_action( 'rewrite_rules_array', array( $this, 'rewrite_rules_array') );
add_filter( 'query_vars', array( $this, 'query_vars' ) );
add_filter( 'template_redirect', array( $this, 'public_template' ) );
}
/**
* Flushes the URL rewrite rules. Needed if the plugin adds its own rules.
*/
function flush_rewrite_rules() {
// global $wp_rewrite;
// $wp_rewrite->flush_rules();
}
/**
* Adds new rewrite rules to the $rules array.
*
* @return array New rewrite rules.
*/
function rewrite_rules_array($rules) {
$newrules = array();
$newrules['wordhub/(.+)'] = 'index.php?wordhub=true&wordhub_repo=$matches[1]';
$newrules['wordhub'] = 'index.php?wordhub=true';
return $newrules + $rules;
}
/**
* Adds query variables to WordPress URLs. Allows us to check if
* ?wordhub=true and other query variables. Used for URL rewriting.
*
* @return array New query variables.
*/
function query_vars($vars) {
array_push($vars, 'wordhub', 'wordhub_repo');
return $vars;
}
/**
* Tells WordPress to use the specified template file if a query variable
* has a certain value. Checks if active theme has the template file, and
* uses that instead of the one included with the plugin.
*/
function public_template() {
global $wp_query;
$wordhub = isset($wp_query->query_vars['wordhub']);
if(!empty($wordhub)) {
// Check if there's a template in the active theme, use the default one if not.
$template = file_exists(TEMPLATEPATH.'/wordhub-template.php') ? TEMPLATEPATH.'/wordhub-template.php' : dirname( __FILE__ ) . '/wordhub-template.php';
include($template);
exit;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment