Rewrite URL for results of a custom WP_Query

I have this form:

<form action="<?php the permalink(); ?>" method="get" >
<input type="hidden" name="taxo" value="question" />
<select name = "cata">
  <option value="unique_name-a">xxx</option>
  <option value="foo">yyy</option>
  <option value="bar">zzz</option>
</select>
<select name ="catb">
  <option value="unique_name-d">xxx</option>
  <option value="unique_name-e">yyy</option>
  <option value="unique_name-f">zzz</option>
</select>
<!-- and more select -->
<button>send</button>
</form>

And this query in a template page:

$query = new WP_Query( array(
  'post_type' =>  'page',
  'tax_query' => array(                   
    'relation' => 'AND',                     
      array(
        'taxonomy' => 'question',   // from $_GET['taxo']            
        'field' => 'slug',                   
        'terms' => array('unique_name-a','unique_name-e','more'), // from my submit form   
        'include_children' => false,          
        'operator' => 'AND'                    
      ),
  )
) );

I would like to play with URL rewriting. I have something like:

http://example.com/?taxo=question&cata=foo&catb=bar&catc=more

I would like the rewritten URL for the above query to be:

http://example.com/questions/cata/foo/catb/bar/catc/…/

EDIT: Why this function is not working?

  function custom_rewrite() {
       add_rewrite_rule(
        'question-tax/test/4/',
        'index.php?tax=question&test=4',
        'top'
        );

      }
      // refresh/flush permalinks in the dashboard if this is changed in any way
      add_action( 'init', 'custom_rewrite' ); 

2 Answers
2

You could try using the add_rewrite_endpoint function, which would actually let you avoid any htaccess modification (unless you need $_GET).

Example:

function add_custom_rewrite_ep() {
    add_rewrite_endpoint('cata', EP_PAGES);
    add_rewrite_endpoint('catb', EP_PAGES);
    add_rewrite_endpoint('catc', EP_PAGES);
}
add_action( 'init', 'add_custom_rewrite_ep' );

Make sure you flush your rewrite rules.

So then, if your URL is /questions/cata/foo/catb/bar/catc/more/, you can access the values with get_query_var like so:

$x = get_query_var('cata','default'); // equals 'foo'
$y = get_query_var('catb','default'); // equals 'bar'
$z = get_query_var('catc','default'); // equals 'more'

It is difficult though to give you an exact solution without knowing how your url’s are generated, if you’re using the $_GET global, and how you’re using the values in your code.

Leave a Comment