WordPress: Using add_query_var to create custom post type URL variables

This post follows on from https://creativedigital.co.nz/wordpress-adding-pagination-to-custom-post-types/

After enabling pagination on our custom post type, we also wished to utilise a URL variable to differentiate between ‘widgets’. This was achieved using the WordPress function ‘add_query_var’ in our functions.php:

Smug Piggy for the Latest Men's & Women's T-shirts
add_filter( 'init', 'add_widget_type_query_var' );
function add_widget_type_query_var()
global $wp;
$wp->add_query_var( 'widget_type' );

With this new variable, we can now query a subset of widgets based on the URL variable supplied eg. widgets.com/widgets/large:

$widget_type = get_query_var( 'widget_type' );

$widget_query_args = array(
'post_type' => 'widgets',
'post_status' => 'publish',
'orderby' => 'title',
'order' => 'ASC',
'posts_per_page' => 4,
'meta_query' => array(
'key' => 'widget_type',
'value' => $widget_type

$widget_query = new WP_Query( $widget_query_args );

Update: Custom pagination fix & rewrite function

In order for WordPress to recognise the new URL variable, we needed to create a new rewrite rule. On top of that, we needed a second rewrite rule to ensure our custom pagination worked with the new URL var.

function add_widget_type_rewrite_rule()

// Fix for custom pagination

Leave a Reply

Your email address will not be published. Required fields are marked *