板邓:wordpress自定义伪静态 WP_Rewrite

阅读wordpress官方文档WP_Rewrite类:https://codex.wordpress.org/Class_Reference/WP_Rewrite

 

案例:

add_filter( 'rewrite_rules_array','my_insert_rewrite_rules' );
add_filter( 'query_vars','my_insert_query_vars' );
add_action( 'wp_loaded','my_flush_rules' );

// flush_rules() if our rules are not yet included
function my_flush_rules(){
    $rules = get_option( 'rewrite_rules' );

    if ( ! isset( $rules['(project)/(\d*)$'] ) ) {
        global $wp_rewrite;
           $wp_rewrite->flush_rules();
    }
}

// Adding a new rule
function my_insert_rewrite_rules( $rules )
{
    $newrules = array();
    $newrules['(project)/(\d*)$'] = 'index.php?pagename=$matches[1]&id=$matches[2]';
    return $newrules + $rules;
}

// Adding the id var so that WP recognizes it
function my_insert_query_vars( $vars )
{
    array_push($vars, 'id');
    return $vars;
}

The Jerome's Keywords plugin does this to enable URLs like http://example.com/tag/sausages.

function keywords_create_rewrite_rules( $rewrite ) {
    global $wp_rewrite;
    
    // add rewrite tokens
    $keytag_token = '%tag%';
    $wp_rewrite->add_rewrite_tag( $keytag_token, '(.+)', 'tag=' );
    
    $keywords_structure = $wp_rewrite->root . "tag/$keytag_token";
    $keywords_rewrite = $wp_rewrite->generate_rewrite_rules( $keywords_structure );
    
    return ( $rewrite + $keywords_rewrite );
}

 




A simpler example of this is Ryan Boren's Feed Director plugin. This simply redirects URLs likehttp://example.com/feed.xml to http://example.com/feed/rss2:

function feed_dir_rewrite( $wp_rewrite ) {
    $feed_rules = array(
        'index.rdf' => 'index.php?feed=rdf',
        'index.xml' => 'index.php?feed=rss2',
        '(.+).xml' => 'index.php?feed=' . $wp_rewrite->preg_index(1)
    );

    $wp_rewrite->rules = $feed_rules + $wp_rewrite->rules;
    return $wp_rewrite->rules;
}

// Hook in.
add_filter( 'generate_rewrite_rules', 'feed_dir_rewrite' );

 

posted @ 2016-11-30 22:25  贵隆  阅读(317)  评论(0编辑  收藏  举报