黄聪:wordpress如何使用wp_rewrite实现自定义伪静态,非301重定向。

今天,想通过wordpress实现

http://hcsem.com/a?h-1

伪静态为

http://hcsem.com/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']; ?>

 

你可能感兴趣的:(wordpress)