Using URL variables on a custom WP_Query

Background

I have a page with a custom template 'listen', with a custom wp_query running on it...

$custom_query_args = array(
    'post_type' = 'post',
    'tax_query' = array(
        array(
            'taxonomy' = 'post_format',
            'field'    = 'slug',
            'terms'    = array( 'post-format-audio' ),
        ),
    ),
);

The Problem

When I try and filter the posts on this page with url variables (example.com/listen/?category_name=thebigshow), nothing changes, even if I spell the category name incorrectly.

How can I use this method to filter the 'listen' page, by 'category_name' (show name)?

Thanks, Andy.

Topic page-template wp-query urls query Wordpress

Category Web


WordPress doesn't handle this logic qutomatically so you will have do do it manually.

What you need to do is:

  1. Read the url parameter with get_query_var( 'category_name' );

  2. injects it in your custom WP_Query:

     $custom_query_args = array(
         'post_type' => 'post',
         'tax_query' => array(
             'relation' => 'AND',
             array(
                 'taxonomy' => 'post_format',
                  'field'    => 'slug',
                  'terms'    => array( 'post-format-audio' ),
              ),
             array(
                 'taxonomy' => 'category',
                  'field'    => 'slug',
                  'terms'    => get_query_var( 'category_name' ),
              )
          )
     );
    

Note that if you decide to pass an arbitrary variable instead of category_name, you will need to declare it before using it.

See https://developer.wordpress.org/reference/functions/get_query_var/

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.