Skip to content

Snippet: Modify any Element’s WP_Query Arguments

Important: You can now enter use the "Advanced Query" setting in any Total module and enter a callback name for the Query arguments. This is more efficient then using the filter mentioned below and also makes it easier for targeting specific grids and re-using custom queries.

Any Total module you use that displays posts (Portfolio Grid, Blog Grid, Post Types Grid...etc) passes it's Query arguments to the "vcex_grid_query" filter which you can use in a child theme to modify the query to set your own custom arguments. See example below:

/**
 * Example for using the"vcex_query_args" filter to tweak a Total element query arguments.
 *
 * Learn more about WP_Query arguments : https://codex.wordpress.org/Class_Reference/WP_Query
 *
 * TIP: You can give any module a unique ID so you can check it using $atts['id'] and target elements
 * exclusively. You could also check the $shortcode_tag to target specific elements like the "wpex_post_cards" only.
 */
add_filter( 'vcex_query_args', function( $args, $atts, $shortcode_tag ) {

	// print_r( $atts ); // Un-comment to view default args.

	// Example to exclude the current post on single posts.
	if ( is_singular() ) {
		$args['post__not_in'] = array( get_the_ID() );
	}

	// Example to show items from the same category for an element shown on portfolio posts.
	if ( is_singular( 'portfolio' ) ) {
		$terms = wp_get_post_terms( get_the_ID(), 'portfolio_category' ); // get post terms
		if ( isset( $terms[0] ) ) {
			$args['tax_query'] = array( array(
				'taxonomy' => 'portfolio_category',
				'field'    => 'slug',
				'terms'    => array( $terms[0]->slug ),
			) );
		}
	}

	// Important return the args!
	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