Created
February 11, 2012 00:41
-
-
Save chrisguitarguy/1794556 to your computer and use it in GitHub Desktop.
WordPress rewrite tutorial
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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 - It can be in functions.php
file.
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
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