I would like to create posts on-the-fly and not store them in the database. For this I'Ve prepeared three steps:
- Setup a custom rewrite rule to match all pages like
- Create the customer query var
- Check the var on
template_redirect
Here's my code:
add_filter( 'rewrite_rules_array', 'rewrite_rules' );
add_filter( 'query_vars', 'set_query_vars' );
add_action( 'template_redirect', 'template_redirect' );
// add custom rewrite rule
function rewrite_rules( $wp_rules ) {
$rules = array();
$rules['^(index\.php/)?my_endpoint/([A-Z0-9_]+)$'] = 'index.php?my_page=$matches[2]';
return $rules + $wp_rules;
}
// define custom query var
function set_query_vars( $vars ) {
$vars[] = 'my_page';
return $vars;
}
// check the query var
function template_redirect() {
// if the endpoint is hit
if ( $page = get_query_var( 'my_page' ) ) {
$post = new WP_Post(
(object) array(
'post_title' => 'my title',
'post_type' => 'page', // not sure about that
'post_content' => 'My content',
)
);
// setup the postdata
setup_postdata( $post );
}
}
I've assumed setup_postdata()
should do the trick by defining the current post.
is_home()
is the only tag which returns true
.