cliff
1/6/2017 - 3:21 PM

Limit Slider Revolution's WP_Query to only include posts with featured images

Limit Slider Revolution's WP_Query to only include posts with featured images

<?php

/**
 * Limit Slider Revolution's WP_Query to only include posts with featured images
 *
 * From https://gist.github.com/cliffordp/9f0d7cc5e86b2a721cd646d953bb1261
 * Similar code for Essential Grid: https://gist.github.com/cliffordp/fbbaad70b9b8748819ac73f00260ac5e
 * Same Slider Revolution code except with additional requirement to be a Featured Event from The Events Calendar: https://gist.github.com/cliffordp/30ac2152a8264ef27235b46b7d16332d
 * 
 * revslider_get_posts filter is from /wp-content/plugins/revslider/includes/framework/functions-wordpress.class.php as of version 4.5.0
 *
 * Filter hook only applies to Slider Revolution > Post-Based Slider > Fetch Posts By Categories & Tags
 * or Slider Revolution > Post-Based Slider > Specific Posts > Specific Posts List (CSV of Post IDs)
 *
 * @return array
 */
function revslider_post_based_require_featured_image( $query, $slider_id ) {
	
	/*
	 * YOU MUST CHANGE THESE
	 * TO YOUR OWN SLIDER REVOLUTION
	 * SLIDER IDs
	 * !!!
	 */
	$slider_ids_to_affect = array( 2, 20, 34 ); // include IDs of sliders to affect
	
	// if this slider is not one to affect, do no filtering
	if ( ! in_array( $slider_id, $slider_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( 'revslider_get_posts', 'revslider_post_based_require_featured_image', 10, 2 );