Restricting bookings by user role

This tutorial is very similar to this tutorial on limiting bookings to one ticket.

At the time of writing, the above article uses an outdated, but still available API. That tutorial shall shortly be updated to reflect this. This tutorial uses the current API.

Restricting bookings by user role

To prevent bookings by users with “non-allowed” roles we can use the eventorganiser_validate_booking_form_submission action. This hooks runs when the booking is being validated, and before it’s created.

By adding an error to the booking form we can prevent the booking being created, whereupon the user will be returned to the booking form with an appropriate error message:

/**
 * Prevents bookings for users not of a white-listed role
 *
 * @param EO_Booking_Form Booking form object
 */
function myprefix_limit_bookee_role( $form ){

    //TODO Change these roles as appropriate
    $allowed_roles = array( 'administrator', 'editor' );

    $user     = new WP_User( get_current_user_id() );
    $has_role = (bool) array_intersect( $user->roles, $allowed_roles );

    if( !$has_role ){
        //This error will prevent the booking from being processed, and display the given error message
        $form->add_error( 'invalid-role', 'You do not have permission to make bookings.' );
    }

}
add_action( 'eventorganiser_validate_booking_form_submission', 'myprefix_limit_bookee_role' );

Please note you will want to update the line $allowed_roles =... to reflect the roles you wish to allow to make bookings.

Hiding the booking form

The above code does what we need it to do. However, if you’re are user who isn’t allowed to make a booking, the booking form still appears. This isn’t ideal, so to remedy this we can use a few lines to prevent the form being added to the page.

Please note you will want to update the line $allowed_roles =... to reflect the roles you wish to allow to make bookings.

/**
 * Hides the booking form if user is not of a white-listed role
 */
function myprefix_maybe_remove_booking_table(){

    //TODO Change these roles as appropriate
    $allowed_roles = array( 'administrator', 'editor' );

    $user     = new WP_User( get_current_user_id() );
    $has_role = (bool) array_intersect( $user->roles, $allowed_roles );

    if( is_singular( 'event' ) && !$has_role ){
        remove_filter( 'the_content', 'eventorganiser_display_booking_table', 999 );
    }

}
add_action( 'wp_head', 'myprefix_maybe_remove_booking_table' );