Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save theeventscalendar/593130a4a059561eb9b0 to your computer and use it in GitHub Desktop.
Save theeventscalendar/593130a4a059561eb9b0 to your computer and use it in GitHub Desktop.
Category archive pages default to List View regardless of the default view set
/**
* Redirect event category requests to list view.
*
* @param $query
*/
function use_list_view_for_categories( $query ) {
// Disregard anything except a main archive query
if ( is_admin() || ! $query->is_main_query() || ! is_archive() ) return;
// We only want to catch *event* category requests being issued
// against something other than list view
if ( ! $query->get( 'tribe_events_cat' ) ) return;
if ( tribe_is_list_view() ) return;
// Get the term object
$term = get_term_by( 'slug', $query->get( 'tribe_events_cat' ), Tribe__Events__Main::TAXONOMY );
// If it's invalid don't go any further
if ( ! $term ) return;
// Get the list-view taxonomy link and redirect to it
header( 'Location: ' . tribe_get_listview_link( $term->term_id ) );
exit();
}
// Use list view for category requests by hooking into pre_get_posts for event queries
add_action( 'tribe_events_pre_get_posts', 'use_list_view_for_categories' );
@cr0ybot
Copy link

cr0ybot commented Dec 13, 2019

This forces list view only without the option to switch to a different view. I wanted to only set the default view for event categories.

Instead of using the tribe_events_pre_get_posts hook, I used the tribe_events_parse_query hook, where the eventDisplay query variable is set.

/**
 * Default event category to list view without redirect.
 */
function event_categories_default_view( $query ) {
	// Disregard anything except a main archive query
	if ( is_admin() || ! $query->is_main_query() || ! is_archive() ) return;

	// We only want to catch *event* category requests being issued
	// against something other than list view
	if ( ! $query->get( 'tribe_events_cat' ) ) return;
	if ( tribe_is_list_view() ) return;

	// If we're on the default view, set to list
	if ( $query->query['eventDisplay'] === 'default' ) { // $query->get('eventDisplay') doesn't work here since it's already been set to something other than 'default'
		$query->set('eventDisplay', 'list');
	}
}
add_action( 'tribe_events_parse_query', 'event_categories_default_view' );

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment