WordPress URL rewrite regex

From the wordpress documentations – https://codex.wordpress.org/Using_Permalinks

Using %category% with multiple categories on a post

When you assign multiple categories to a post, only one can show up in
the permalink. The categories are ordered alphabetically. In each
group of sub-categories the order will also be alphabetical. (see
Manage Categories). The post will still be accessible through all the
categories as normal.

You can however reach what you want by creating a page with the slug listpublications and adding the folllowing code:

add_action('init', 'rewrite');
add_filter('query_vars', 'query_vars');

function rewrite(){
    add_rewrite_rule('listpublications/([^/]+)/([^/]+)/?$', 'index.php?pagename=listpublications&magazine=$matches[1]&issue=$matches[2]','top');
}

function query_vars($query_vars) {
    $query_vars[] = 'magazine';
    $query_vars[] = 'issue';
    return $query_vars;
}

Now go to settings -> permalinks and click save. This will add the new rewrite rules, so this is very important.

Now create a template file in your theme folder named page-listpublications.php and add the following code between the footer and header.

 global $wp_query;

    $query_args = array(
    // show all posts matching this query
        'posts_per_page'    =>   -1,
    // show the 'publications' custom post type
        'post_type'         =>   'publications',
        // query for you custom taxonomy stuff
        'taq_query' => array(
            array(
                'taxonomy'  =>   'magazine',
                'field'     =>   'slug',
                'terms'     =>   $wp_query->query_vars['magazine']
                ),
            array(
                'taxonomy'  =>   'issue',
                'field'     =>   'slug',
                'terms'     =>   $wp_query->query_vars['issue']
                )
            )

        );

   //fetch results from DB
    $query = new WP_Query( $query_args );

    if ($query->have_posts()):  while ($query->have_posts()): $query->the_post(); 
     // do something sweet with the results
    the_content();

Visiting www.yourdomain.com/listpublications/test-mag/2016-aug should give you all publications in test magazine and in issue 2016-aug.

Hope this helps 🙂

Leave a Comment