Skip to content

Snippet: Custom Post Cards Filter Using URL Parameters

The Total theme lets you create AJAX filters using the Post Cards element. But what if you want to filter items dynamically based on custom URL parameters?

With a bit of custom code, you can easily build a custom filter for any Post Cards element by hooking into the totalthemecore/vcex/post_query/args filter and modifying the WP_Query arguments accordingly.

You might wonder why the theme doesn’t handle URL parameters automatically. This would poses significant security risks, cause conflicts, and it’s impossible for the theme to guess which “friendly” URL parameter names you want to use. Using custom code is the safer and more flexible solution.

In the future, we may update the Post Cards element to allow you to define a list of filter parameters it listens to, so you won’t need custom code. In the meantime, you can use this snippet to achieve the functionality you need.

/**
 * Supports a custom filter based on URL parameters for the Post Cards Element
 * with the 'YOUR_UNIQUE_CARDS_ID' Unique ID.
 */
add_filter( 'totalthemecore/vcex/post_query/args', function( $args, $shortcode_atts, $shortcode_tag ) {
	// Only target the specific Post Cards element by unique_id
	if ( empty( $shortcode_atts['unique_id'] ) || 'YOUR_UNIQUE_CARDS_ID' !== $shortcode_atts['unique_id'] ) {
		return $args;
	}

	// Example: Check for a taxonomy filter in the URL, e.g. ?color=red
	if ( ! empty( $_GET['color'] ) ) {
		$taxonmy    = 'color';
		$color_term = sanitize_text_field( wp_unslash( $_GET['color'] ) );

		// If the term exists in the 'color' taxonomy add the new tax_query argument
		if ( term_exists( $color_term, $taxonomy ) ) {
			$tax_query_item = [
				'taxonomy' => $taxonmy,
				'field'    => 'slug',
				'terms'    => $color_term,
			];

			if ( ! empty( $args['tax_query'] ) && is_array( $args['tax_query'] ) ) {
				$args['tax_query'][] = $tax_query_item;
			} else {
				$args['tax_query'] = [ $tax_query_item ];
			}
		}
	}

	// Check for order from URL, e.g. ?order=ASC or DESC
	if ( ! empty( $_GET['order'] ) && in_array( strtoupper( $_GET['order'] ), [ 'ASC', 'DESC' ], true ) ) {
		$args['order'] = strtoupper( $_GET['order'] );
	}

	// Check for orderby from URL, e.g. ?orderby=date or title
	$valid_orderbys = [ 'date', 'title', 'menu_order' ]; // add more if needed
	if ( ! empty( $_GET['orderby'] ) && in_array( $_GET['orderby'], $valid_orderbys, true ) ) {
		$args['orderby'] = $_GET['orderby'];
	}

	return $args;
}, 10, 3 );
All PHP snippets should be added via child theme's functions.php file or via a plugin.
We recommend Code Snippets (100% Free) or WPCode (sponsored)
Back To Top