Skip to content

Instantly share code, notes, and snippets.

@chrisguitarguy
Created February 11, 2012 00:41
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 8 You must be signed in to fork a gist
  • Save chrisguitarguy/1794556 to your computer and use it in GitHub Desktop.
Save chrisguitarguy/1794556 to your computer and use it in GitHub Desktop.
WordPress rewrite tutorial
<?php
/*
Plugin Name: Rewrite Rule Tutorials
*/
add_action( 'init', 'pmg_rewrite_add_rewrites' );
function pmg_rewrite_add_rewrites()
{
add_rewrite_endpoint( 'json', EP_PERMALINK );
add_rewrite_rule(
'^p/(\d+)/?$', // p followed by a slash, a series of one or more digets and maybe another slash
'index.php?p=$matches[1]',
'top'
);
add_rewrite_tag( '%form%', '[^/]' );
add_rewrite_rule(
'^submit/?$',
'index.php?form=true',
'top'
);
add_feed( 'json', 'pmg_rewrite_json_feed' );
}
function pmg_rewrite_json_feed()
{
$posts = get_posts();
$out = array();
foreach( $posts as $p )
{
$out[] = array(
'title' => $p->post_title,
'content' => $p->post_content
);
}
header('Content-Type: text/plain');
echo json_encode( $out );
}
register_activation_hook( __FILE__, 'pmg_rewrite_activation' );
function pmg_rewrite_activation()
{
pmg_rewrite_add_rewrites();
flush_rewrite_rules();
}
add_action( 'template_redirect', 'pmg_rewrite_catch_form' );
function pmg_rewrite_catch_form()
{
if( is_singular() && get_query_var( 'json' ) )
{
$post = get_queried_object();
$out = array(
'title' => $post->post_title,
'content' => $post->post_content
);
header('Content-Type: text/plain');
echo json_encode( $out );
exit();
}
}
//add_filter( 'query_vars', 'pmg_rewrite_add_var' );
function pmg_rewrite_add_var( $vars )
{
$vars[] = 'form';
return $vars;
}
add_filter( 'request', 'pmg_rewrite_filter_request' );
function pmg_rewrite_filter_request( $vars )
{
if( isset( $vars['json'] ) ) $vars['json'] = true;
return $vars;
}
@vwasteels
Copy link

Hello !

thanks for this code ! quick question : does this have to be in a plugin or it can live in the main function.php of my theme ?

Thanks again

@mikeschinkel
Copy link

@vwasteels - It can be in functions.php file.

@dechowdev
Copy link

If I get this correctly...
As I read in the blog post, and around the web...

You have to register your custom variables/params to the rewrite rule?
Because that basically every rule goes through to the index.php?

Am I on to something here or have I misread something? :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment