Wordpress simple rewrite rule not working

前端 未结 3 1490
名媛妹妹
名媛妹妹 2021-01-24 12:44

I\'m trying to create a rewrite rule in Wordpress to create direct pretty links to search results.

I\'m working with a custom post type called \'object\'

My resu

3条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-24 13:07

    OK, I've finnaly found a way to achieve this.

    Here is the code I added to my theme:

    function custom_rewrite( $wp_rewrite ) {
        $feed_rules = array(
            'objects/(.+)'  =>  'index.php?page_id=27&filtre=' . $wp_rewrite->preg_index(1),
        );
        $wp_rewrite->rules = $feed_rules + $wp_rewrite->rules;
    }
    

    where 27 is the Wordpress ID of the "/objects" page I want to reach with the rewritten URL, and:

    function custom_wp_querystring() {
        add_rewrite_tag('%filtre%','([^&]+)');
    }
    

    In order to tell Wordpress I need to use a custom query var called "filtre".

    This last function must be added on init action:

    add_action( 'init', 'custom_wp_querystring');
    add_filter( 'generate_rewrite_rules', 'custom_rewrite' );
    

    Important thing to know, in my page template (the one with ID 27 in my example), if I want to test the query var, it's not possible to do that kind of test:

    if ( isset ( $_GET['filtre'] ) ) { ... }
    

    GET vars are 'hidden' due to Wordpress redirection, you must then do:

    if ( isset( $wp_query->query_vars['filtre'] ) ) { ... }
    

提交回复
热议问题