Search code examples
phpwordpress

Extending wordpress adding extra path information to a page URL


I have a page with a URL like http://example.com/pagename?query=foo. I can get that query=foo data using the get_query_var method. But for convenience, I need to replace it with something like http://example.com/pagename/foo To make it work, I must convince WordPress that pagename/foo is pagename with extra information. But I can't find a way to do that.

I looked up the Wordpress documentation and googled for it, but I am unable to use the proper words to find a solution, or there is none, as I can't find anything.


Solution

  • This is an answer based on Chris Haas comment.

    I used this code snippet to do the rewrite of pesquisa/?word=something to index.php?pagename=pesquisa&word=something:

    function gp_rewrite() {
      add_rewrite_rule('^pesquisa/([^/]+)/?',
                       'index.php?pagename=pesquisa&word=$matches[1]', 'top');  
    }
    

    In order for this function to evaluate, I needed this:

    add_action( 'init', 'gp_rewrite' );
    

    I also needed to declare the query variable:

    function dacl_register_query_var( $qvars ) {
        $qvars[] = 'word';
        return $qvars;
    }
    

    Finally, my search function does this:

    function dacl_search_word() {
        
        $query = rawurldecode(get_query_var("word"));
        ...
    

    Note the rawurldecode, otherwise I got utf8 characters double encoded.

    Finally, do not forget to go to the Settings -> Permanent Links page in your Wordpress installation and hit save, to force the permanent link cache to be updated.