Skip to content

Instantly share code, notes, and snippets.

@nhatnx
Forked from chrisguitarguy/pmg-rewrite.php
Created October 11, 2017 05:37
Show Gist options
  • Save nhatnx/7fb844baaf53bee9dd23203a2701b025 to your computer and use it in GitHub Desktop.
Save nhatnx/7fb844baaf53bee9dd23203a2701b025 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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment