今天,想通过wordpress实现http://xxx/a?h-1伪静态为http://xxx/a-1.html找了很多资料,终于搞定。
只需要在functions.php文件中添加如下代码即可:


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['a-(.*).html$'] ) ) {
        global $wp_rewrite;
           $wp_rewrite->flush_rules();
    }
}

// Adding a new rule
function my_insert_rewrite_rules( $rules )
{
    $newrules = array();
    $newrules['a-(.*).html$'] = 'index.php?pagename=a&h=$matches[1]';
    return $newrules + $rules;
}

function my_insert_query_vars( $vars )
{
    array_push($vars, 'h');
    return $vars;
}

如何在page-a里面获取到h值呢?复制下面代码即可:


<? echo $wp_query->query_vars['h']; ?>