Skip to content

Instantly share code, notes, and snippets.

@bdeleasa
Created October 29, 2019 18:17
Show Gist options
  • Save bdeleasa/c8c6ccfde6fb3393b452548e66e20cb9 to your computer and use it in GitHub Desktop.
Save bdeleasa/c8c6ccfde6fb3393b452548e66e20cb9 to your computer and use it in GitHub Desktop.
Removes any 'Events' menu items if there aren't any upcoming events. Meant to be used with The Events Calendar plugin.
<?php
/**
* The plugin bootstrap file
*
* This file is read by WordPress to generate the plugin information in the plugin
* admin area. This file also includes all of the dependencies used by the plugin,
* registers the activation and deactivation functions, and defines a function
* that starts the plugin.
*
* @link http://briannadeleasa.com
* @since 0.0.1
* @package TEC_Menu_Items
*
* @wordpress-plugin
* Plugin Name: The Events Calendar - Menu Items
* Plugin URI: https://briannadeleasa.com
* Description: Conditionally shows or hides an 'events' menu item based on whether any upcoming events exist.
* Version: 1.0.0
* Author: Brianna Deleasa
* Author URI: http://briannadeleasa.com
* License: GPL-2.0+
* License URI: http://www.gnu.org/licenses/gpl-2.0.txt
* Text Domain: the-events-calendar-menu-items
* Domain Path: /languages
*/
/**
* Queries the database to find out how many upcoming events there are.
*
* We're also setting a transient because this likely won't change from page to page,
* so why re-run the query if we don't need to.
*
* @since 1.0.0
*
* @return int
*/
function tecmi_get_upcoming_events_count() {
$transient_key = 'tecmi_upcoming_events_count';
$count = get_transient( $transient_key );
if ( ! empty( $count ) ) {
return $count;
}
// Set query arguments
$args = array(
'post_type' => 'tribe_events',
'meta_query' => array(
array(
'key' => '_EventStartDate',
'value' => date('Y-m-d') . ' 00:00:00',
'compare' => '>='
)
)
);
// Generate query
$events_query = new WP_Query( $args );
// Save the event count
set_transient( $transient_key, $events_query->post_count, 4800 );
return $events_query->post_count;
}
add_filter( 'wp_nav_menu_objects', 'tecmi_remove_events_menu_item', 10, 2 );
/**
* Loops through all menu items to remove any with a title 'Events'.
*
* We're only removing the events menu item when there aren't any upcoming events on
* the current site.
*
* @since 1.0.0
*
* @param $sorted_menu_objects array
* @param $args array
* @return array
*/
function tecmi_remove_events_menu_item( $sorted_menu_objects, $args ) {
$event_count = tecmi_get_upcoming_events_count();
// Get out if there are upcoming events
if ( $event_count >= 1 ) {
return $sorted_menu_objects;
}
// Loop through and remove any menu items with the title 'Events'
foreach ($sorted_menu_objects as $key => $menu_object) {
if ( stristr( $menu_object->title, 'Events' ) ) {
unset($sorted_menu_objects[$key]);
break;
}
}
return $sorted_menu_objects;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment