Home > Software design >  Rewrite url condition on Wordpress for multiple items
Rewrite url condition on Wordpress for multiple items

Time:06-27

wanted to add a rewrite rule to turn this:

/compare/?items=test1,test2

into this

/compare/test1-vs-test2

Also there could be up to 4 items sent to the URL so that the outcome would be

/compare/test1-vs-test2-vs-test3-vs-test4

Can this be achieved using https://developer.wordpress.org/reference/functions/add_rewrite_rule/ ?

Or should I add some conditions directly into .htaccess? Any help would be appreciated. Thank you.

CodePudding user response:

  1. Add the items query var
    function compare_query_vars( $qvars ) {
        $qvars[] = 'items';
        return $qvars;
    }
    add_filter( 'query_vars', 'compare_query_vars' );
  1. The loop query will look something like this:
    $items = get_query_var( 'items');
    $items = explode('-vs-',$items);
    
    $the_query = new WP_Query( [ 'post_name__in' => $items ]  );

Result: /?items=test1-vs-test2

Note: when you are constructing the initial url make sure you are sending the slug of the post and not the ID

  1. An finally the URL rewrite
    add_action( 'init',  function() {
        add_rewrite_rule( '^compare/([a-z0-9-] )[/]?$', 'index.php?page_id=37&items=$matches[1]', 'top' );
    } );

Note: page_id should be the ID of the page where you are creating the loop

  1. Flush Permalinks by going to Settings -> Permalinks and just save the page.
  2. Access the desired URL /compare/test1-vs-test2
  • Related