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(
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.

add_action('init','add_widget_type_rewrite_rule');
function add_widget_type_rewrite_rule()
{
add_rewrite_rule(
'^widgets\/([^/]*)$',
'index.php?page_id=12&widget_type=$matches[1]',
'top'
);

// Fix for custom pagination
add_rewrite_rule(
'^widgets\/([^/]*)\/page\/([0-9]*)?',
'index.php?page_id=12&widget_type=$matches[1]&paged=$matches[2]',
'top'
);
}

Leave a Reply

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