zoukankan      html  css  js  c++  java
  • 板邓: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' );
    板邓个人博客:http://8dseo.com
  • 相关阅读:
    Java debug技术
    mybatis-generator插件
    JVM常见问题
    Java安全之Access control
    JVM新生代各个区的比例问题
    宣告
    退役啦!
    NOIP 2018退役祭
    自定义博客园模板
    带花树算法
  • 原文地址:https://www.cnblogs.com/xbdeng/p/6119991.html
Copyright © 2011-2022 走看看