Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

vwasteels commented May 15, 2013

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

This comment has been minimized.

Copy link

mikeschinkel commented Mar 13, 2014

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

@Dechowmedia

This comment has been minimized.

Copy link

Dechowmedia commented Apr 7, 2014

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
You can’t perform that action at this time.