Limit number of events shown only on specific pages
The use case for this snippet is a calendar, e.g. using the list view, that displays the next X upcoming events on the home page, with a link to view the full grid view calendar below.
On the home page calendar, we only want a limited number of events to be shown, but we don't want to alter the number of events across all calendars on the site.
This example snippet will limit a calendar on the site's static home page to the next 4 events that occur in time, starting from today.
This snippet could be altered to check for different criteria, such as post ID, if you have a calendar on a page other than the static home page that you want to alter the number of events for.
To use this snippet, add it via functions.php, a custom functionality plugin, or your favorite code snippets plugin.
add_filter( 'piecal_events_array_filter', 'piecal_custom_limit_events', 10, 4 ); function piecal_custom_limit_events( $eventsArray, $rangeStart = null, $rangeEnd = null, $appendOffset ) { // Only alter the events array on the static front page if( !is_front_page() ) return $eventsArray; // First, we need to make sure only events on today or after are in the events array $eventsArray = array_filter($eventsArray, function($event) { // First, ensure that 'start' is in a comparable date format $eventStartDate = new DateTime($event['start']); $currentDate = new DateTime(); // This defaults to "now" // Return true for events starting today or in the future return $eventStartDate >= $currentDate; }); // Reset the indexes after filtering $eventsArray = array_values($eventsArray); // Next, we need to limit how many are actually in the array // In this case, I'm keeping the first 4. $eventsArray = array_slice($eventsArray, 0, 4); return $eventsArray; }