Setup a custom dynamic post

Question

I would like to create posts on-the-fly and not store them in the database. For this I’Ve prepeared three steps:

  1. Setup a custom rewrite rule to match all pages like https://example.com/my_page/WHATEVER
  2. Create the customer query var
  3. 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.

--------------------------------------------------

>>> Share a link to this question, just copy and paste the code bellow on your web page <<<

<a href="https://www.wptricks.com/question/setup-a-custom-dynamic-post/">

Setup a custom dynamic post</a>
0
, Xaver 2 months 0 Answers 75 views 0

Leave an answer