Skip to content

Instantly share code, notes, and snippets.

@cliffordp
Last active May 18, 2022 03:14
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cliffordp/ddb9e11015c193afd1eea78a54afdf79 to your computer and use it in GitHub Desktop.
Save cliffordp/ddb9e11015c193afd1eea78a54afdf79 to your computer and use it in GitHub Desktop.
The Events Calendar (TEC) and Event Tickets (ET): Get the total number of unique events for which a user has obtained tickets (of any kind, including RSVP) within the specified Event Category.
<?php
/**
* The Events Calendar (TEC) and Event Tickets (ET): Get the total number of unique events for which a user has
* obtained tickets (of any kind, including RSVP) within the specified Event Category.
*
* Could be turned into a shortcode. Could be used in a way to output a friendly message like,
* "Thanks for attending *14* events in the *Sports* category."
* This function currently gives you the *14* part of this message but could easily be extended.
*
* @link https://gist.github.com/cliffordp/ddb9e11015c193afd1eea78a54afdf79 This snippet.
*
* @see tribe_events()
* @see tribe_attendees()
*
* @param int $tec_cat_id
* @param int $user_id If not specified, will use the currently logged in user.
*
* @return int|false
*/
function cliff_et_get_count_of_events_user_obtained_ticket_for( $tec_cat_id, $user_id = 0 ) {
// Bail if bad request.
if (
! function_exists( 'tribe_events' )
|| ! function_exists( 'tribe_attendees' )
|| ! is_int( $user_id )
|| ! is_int( $tec_cat_id )
) {
return false;
}
// If no User ID passed, get currently logged in user.
if ( 0 === $user_id ) {
$user_id = get_current_user_id();
}
/**
* Get all the event IDs that are in the specified event category that also have a ticket assigned (to help reduce
* the foreach looping).
*
* @see Tribe__Events__Repositories__Event
*/
$events = tribe_events();
$events->by_args(
[
'event_category' => $tec_cat_id,
'cost_greater_than' => - 1, // has any type of ticket (even free or RSVP)
]
);
$event_ids = $events->get_ids();
$user_event_attendance_count = 0;
foreach ( $event_ids as $event_id ) {
/**
* Get all the attendees for this user (and optionally for a specific set of events).
*
* @see Tribe__Tickets__Attendee_Repository
* @see Tribe__Tickets_Plus__Attendee_Repository
*/
$attendees = tribe_attendees();
// Enable found() calculations.
$attendees->set_found_rows( true );
// Do the filtering.
$args = [
'user' => $user_id,
'event' => $event_id,
];
$attendees->by_args( $args );
if ( 0 < $attendees->found() ) {
$user_event_attendance_count ++;
}
}
return $user_event_attendance_count;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment