Skip to content

Instantly share code, notes, and snippets.

@jaggy
Created April 7, 2014 10:31
Show Gist options
  • Save jaggy/10017952 to your computer and use it in GitHub Desktop.
Save jaggy/10017952 to your computer and use it in GitHub Desktop.
<?php
/**
* A wordpress rewrite wrapper
*
* @param string $alias
* @param string $url
* @return null
*/
function connect( $alias, $url )
{
$this->routes[ $alias ] = $url;
$temporary = array_filter(explode( '/', $url ));
$pagename = reset( $temporary );
$parameters = array();
$arguments = array();
// the pattern for detecting parameters
$pattern = '/[:]([a-zA-Z_]+)/';
$replacement = '([^/]*)';
// detect all the parameters
preg_match_all( $pattern, $url, $parameters );
$parameters = end( $parameters );
$arguments = array_pad( $arguments, count($parameters), '([^/]+)' );
// generate the rule
$rule = "({$pagename})/" . implode( '/', $arguments ) . "/?$";
// generate the full path
$path = "index.php?pagename=\$matches[1]&";
foreach( $parameters as $key => $parameter )
{
$id = $key + 2;
$path .= "{$parameter}=\$matches[{$id}]&";
}
$path = rtrim( $path, '&' );
// push the rewrite rules in
add_filter( 'rewrite_rules_array', function( $rules ) use ( $rule, $path ) {
$new_rules = array( $rule => $path );
// push your rules first for priority
return $new_rules + $rules;
});
// make sure that the parameters are set in `get_query_vars`
add_filter( 'query_vars', function( $vars ) use ( $parameters ){
foreach( $parameters as $parameter )
array_push( $vars, $parameter );
return $vars;
});
// flush the rules
add_action( 'template_redirect', function() use ( $rule ) {
$rules = get_option( 'rewrite_rules' );
if(isset( $rules[ $rule ] ))
return;
global $wp_rewrite;
$wp_rewrite->flush_rules();
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment