cliff
2/2/2017 - 5:30 AM

Limit Essential Grid's WP_Query to only include posts with featured images

Limit Essential Grid's WP_Query to only include posts with featured images

<?php

/**
 * Limit Essential Grid's WP_Query to only include posts with featured images
 *
 * From https://gist.github.com/cliffordp/fbbaad70b9b8748819ac73f00260ac5e
 * Similar code for Slider Revolution: https://gist.github.com/cliffordp/9f0d7cc5e86b2a721cd646d953bb1261
 * Same Essential Grid code except with additional requirement to be a Featured Event from The Events Calendar: https://gist.github.com/cliffordp/a6aad3c60f469970b1ecb209d85ec755
 * 
 * essgrid_get_posts filter is from /wp-content/plugins/essential-grid/includes/base.class.php
 *
 * Tested working with version 2.1.0.2
 *
 * Filter hook only applies to Essential Grid > Source > Source Based on Posts, Pages, Custom Posts
 *
 * @return array
 */
function essgrid_post_based_require_featured_image( $query, $grid_id ) {
	
	/*
	 * YOU MUST CHANGE THESE
	 * TO YOUR OWN ESSENTIAL GRID
	 * GRID IDs
	 * !!!
	 */
	$grid_ids_to_affect = array( 1, 2, 14 ); // include IDs of grids to affect
	
	// if this grid is not one to affect, do no filtering
	if ( ! in_array( $grid_id, $grid_ids_to_affect ) ) {
		return $query;
	}
	
	// get the existing meta_query so we aren't wiping that out
	if ( ! empty( $query['meta_query'] ) ) {
		$meta_query = (array) $query[ 'meta_query' ];
	} else {
		$meta_query = array();
	}

	// do the filtering...

	// has a Featured Image
	$meta_query[] = array(
		'key' => '_thumbnail_id',
		'compare' => 'EXISTS',
	);

	$query['meta_query'] = $meta_query;
	
	return $query;
}
 
add_filter( 'essgrid_get_posts', 'essgrid_post_based_require_featured_image', 10, 2 );