最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

wp query - Setup a custom dynamic post

programmeradmin1浏览0评论

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
  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.

发布评论

评论列表(0)

  1. 暂无评论