linkedin

Topics

⌘K
  1. Home
  2. /
  3. Docs
  4. /
  5. Topics
  6. /
  7. Code Snippets

Code Snippets

This is a Developer-level document. If you are unfamiliar with code/templates and resolving potential conflicts, please engage with a developer who is familiar with FooEvents and/or WooCommerce.

Important, please read first #

These snippets are provided as a courtesy and do not form part of the FooEvents product offering. They are considered customizations and are not officially supported by FooEvents. As such, we do not provide support for snippets and customizations as per our Terms of Service. Please use at your own risk.

Automatically complete orders #

This allows tickets to be automatically sent once payment has been received instead of having to manually complete the order. Please ensure that your event products are set to “Virtual” and “Downloadable” as explained in our help documentation, otherwise, the order will not complete automatically even if payment was made.

Add the following code your child theme’s functions.php file or via a plugin that allows custom functions to be added, such as the Code Snippets plugin. Avoid adding custom code directly to your parent theme’s functions.php file as it will be overwritten when you update the theme.

You could also change the “Completed” status to be another order status such as “Processing”.

/**
 * Auto Complete all WooCommerce orders.
 */
add_action( 'woocommerce_thankyou', 'custom_woocommerce_auto_complete_order' );
function custom_woocommerce_auto_complete_order( $order_id ) { 
    if ( ! $order_id ) {
        return;
    }

    $order = wc_get_order( $order_id );
    $order->update_status( 'completed' );
}

Show attendee name and email in the New Order admin email #

Add the following code snippet to your theme’s functions.php file. You can change the email that this is displayed in by using a different hook.

add_action( 'woocommerce_email_customer_details', 'fooevents_display_attendee_details_in_new_order_email', 10 , 4);
function fooevents_display_attendee_details_in_new_order_email($order, $sent_to_admin, $plain_text, $email){
    echo "<h3>Attendee Details</h3>";
    $WooCommerceEventsOrderTickets = get_post_meta($order->get_id(), 'WooCommerceEventsOrderTickets', true);
    foreach($WooCommerceEventsOrderTickets as $event) {
        foreach($event as $ticket) {
            echo "<p>";
            echo '<strong>First Name</strong>: '.$ticket['WooCommerceEventsAttendeeName'].'<br />';
            echo '<strong>Last Name</strong>: '.$ticket['WooCommerceEventsAttendeeLastName'].'<br />';
            echo '<strong>Email Address</strong>: '.$ticket['WooCommerceEventsAttendeeEmail'].'<br />';
            echo "</p>";
        }
    }
}

Show all custom attendee fields without labels in the New Order admin email #

Add the following code snippet to your theme’s functions.php file. You can change the email that this is displayed in by using a different hook.

add_action( 'woocommerce_email_customer_details', 'fooevents_display_attendee_details_in_new_order_email', 10 , 4);
function fooevents_display_attendee_details_in_new_order_email($order, $sent_to_admin, $plain_text, $email){
    echo "<h3>Attendee Details</h3>";
    $WooCommerceEventsOrderTickets = get_post_meta($order->get_id(), 'WooCommerceEventsOrderTickets', true);
    foreach($WooCommerceEventsOrderTickets as $event) {
        foreach($event as $ticket) {
            echo "<p>";
            echo '<strong>First Name</strong>: '.$ticket['WooCommerceEventsAttendeeName'].'<br />';
            echo '<strong>Last Name</strong>: '.$ticket['WooCommerceEventsAttendeeLastName'].'<br />';
            echo '<strong>Email Address</strong>: '.$ticket['WooCommerceEventsAttendeeEmail'].'<br />';
            foreach ($ticket['WooCommerceEventsCustomAttendeeFields'] as $caf) {
                 echo $caf.'<br />';
            }
            echo "</p>";
        }
    }
}

Show custom attendee fields with labels in the New Order admin email #

Add the following code snippet to your theme’s functions.php file. You can change the email that this is displayed in by using a different hook. Make sure to replace “ovsxtmynwagotamjqieq” and “ruzwhgbuhzuzzdwnnaxe” in the example code with your specific custom attendee field code. You can find this information if you edit a ticket and look for each custom attendee field in the “Custom Fields” section. You would need to add each custom attendee field and its label individually.

add_action( 'woocommerce_email_customer_details', 'fooevents_display_attendee_details_in_new_order_email', 10 , 4);
function fooevents_display_attendee_details_in_new_order_email($order, $sent_to_admin, $plain_text, $email){
    echo "<h3>Attendee Details</h3>";
    $WooCommerceEventsOrderTickets = get_post_meta($order->get_id(), 'WooCommerceEventsOrderTickets', true);
    foreach($WooCommerceEventsOrderTickets as $event) {
        foreach($event as $ticket) {
            echo "<p>";
            echo '<strong>First Name</strong>: '.$ticket['WooCommerceEventsAttendeeName'].'<br />';
            echo '<strong>Last Name</strong>: '.$ticket['WooCommerceEventsAttendeeLastName'].'<br />';
            echo '<strong>Email Address</strong>: '.$ticket['WooCommerceEventsAttendeeEmail'].'<br />';
            echo '<strong>Birthday</strong>: '.$ticket['WooCommerceEventsCustomAttendeeFields']['fooevents_custom_ovsxtmynwagotamjqieq'].'<br />';
            echo '<strong>Favorite song</strong>: '.$ticket['WooCommerceEventsCustomAttendeeFields']['fooevents_custom_ruzwhgbuhzuzzdwnnaxe'].'<br />';
            echo "</p>";
        }
    }
}

Display event start time on the event listing #

Add the following code snippet to your theme’s functions.php file. Style the display of the time by adding CSS for the class ‘fooevents-date’.

Change the placement of the time by using a different hook.

function fooevents_display_time_in_shop_listing() {
global $post;
if (is_front_page() || is_home() || is_shop() || is_product_category() || is_product_tag()) {
echo '<div class="fooevents-date">';
echo get_post_meta($post->ID, 'WooCommerceEventsHour', true).':';
echo get_post_meta($post->ID, 'WooCommerceEventsMinutes', true). ' ';
echo get_post_meta($post->ID, 'WooCommerceEventsPeriod', true);
echo '</div>';
}
}
add_filter( 'woocommerce_after_shop_loop_item_title', 'fooevents_display_time_in_shop_listing', 35 );

Display registered attendees in a table format #

Add the following code snippet to your theme’s functions.php file to output all registered attendees to your event in a table grid format. After adding the code snippet, you can use the shortcode like this:

[fooevents_attendees]

to display all attendees for all events, or like this:

[fooevents_attendees product_id=123]

where “123” is the ID of the event for which you want to display the attendee list for.

function fooevents_display_attendees($attributes) {
 
  $product_id='';
  if(!empty($attributes['product_id'])) {
    $product_id = $attributes['product_id'];
  }

  $output ='';
  $args = array(
    'numberposts' => -1,
    'posts_per_page' => -1,
    'post_type'   => 'event_magic_tickets',
    'meta_query'  => array(
      'relation'    => 'OR',
      array(
        'key'   => 'WooCommerceEventsProductID',
        'value'   => $product_id,
        'compare' => 'LIKE'
      )
    )
  );  

   $the_query = new WP_Query( $args );

  if( $the_query->have_posts() ):
    while ( $the_query->have_posts() ) : $the_query->the_post();
    $postid = $the_query->post->ID;
     
      // output all findings - CUSTOMIZE TO YOUR LIKING
      $output .= "<tr>";
      $output .= "<td>".get_the_title()."</td>";
      $output .= "<td>".get_post_meta($postid, 'WooCommerceEventsPurchaserFirstName', true)."</td>";
      $output .= "<td>".get_post_meta($postid, 'WooCommerceEventsPurchaserLastName', true)."</td>";
      $output .= "</tr>";
         
    endwhile;
  endif;
  wp_reset_query();
  $output ="<table>".$output."</table>";
  return $output;
   
}
add_shortcode("fooevents_attendees", "fooevents_display_attendees");

Display the event date before the title on the product page #

Change the placement of the date by using a different hook.

function fooevents_display_date_on_single() {
  global $post;
  $product = wc_get_product( $post->ID );
  $start_date = $product->get_meta( 'WooCommerceEventsDate' );
  $end_date = $product->get_meta( 'WooCommerceEventsEndDate' );
  if ( $end_date ) {
    printf(
      '<h3>%s</h3>',
      esc_html( $start_date . ' - ' . $end_date )
    );
  } else if( $start_date ) {
    printf(
      '<h3>%s</h3>',
      esc_html( $start_date )
    );
  }
}
add_action( 'woocommerce_single_product_summary', 'fooevents_display_date_on_single' );

If you would like to make the event date available as a shortcode, you can add the following line below the function:

add_shortcode( 'fooevents_date_on_single', 'fooevents_display_date_on_single');

Then you can use the shortcode [fooevents_date_on_single] to display the event date on the page.

Replace the seat icon on the seating chart with a different image #

Modify the following CSS code snippet by adding the URL to a different image that you would like to replace the default seat image for all seats. Add the modified code snippet to your theme’s custom CSS file.

#fooevents_seating_dialog .fooevents_seating_chart_view_row span {
  background-image: url(../images/seat.svg);
}

Remove the seat icon on the seating chart so that seats display as boxes #

#fooevents_seating_dialog .fooevents_seating_chart_view_row span {
  background-image: none;
}

Change the direction of the seat numbers on the seating chart #

#fooevents_seating_dialog .fooevents_seating_chart_view_row {
  display: flex;
  flex-direction: row-reverse;
  justify-content: flex-end;
}

Show odd-numbered seats on the right and even-numbered seats on the left #

#fooevents_seating_dialog .fooevents_seating_chart_view_row > span:nth-of-type(even) {
  float: left;
}

Display seats in the middle of the seating chart #

#fooevents_seating_dialog .fooevents_seating_chart_view_row_name,
#fooevents_seating_dialog .fooevents_seating_chart_view_row {
  text-align: center;
}

Let the seating chart scroll horizontally instead of displaying seats in the next row #

This could be useful if you have many seats per row and you want them to display next to each other instead of on the next row if they do not fit on one line.

#fooevents_seating_dialog .fooevents_seating_chart_view_row {
  overflow-x: scroll;
  white-space: nowrap;
}

Show a calendar grid on desktops and a calendar week list on mobile #

Add two calendar shortcodes on the page or post where you want to display your calendar. The first shortcode will display a calendar grid and should look like this:

[fooevents_calendar id="desktop"]

The second shortcode will display a calendar week list and should look like this:

[fooevents_calendar id="mobile" defaultView="listWeek"]

Add the following CSS code snippet to your theme’s custom CSS file. Make sure that the CSS ID selector value is the same as the value of the “id” attribute that you’ve specified in the shortcode. You can adjust the “max-width” property to the screen size where you want the calendar week list to show and the calendar grid to be hidden.

#desktop_fooevents_calendar {
  display: block;
}
    
#mobile_fooevents_calendar {
  display: none;
}
    
@media screen and (max-width: 600px) {
  #desktop_fooevents_calendar {
    display: none;
  }
    
  #mobile_fooevents_calendar {
    display: block;
  }    
}

Change the position of the Copy Purchaser’s Details icon #

The following snippet will align the copy button to the right of the first name label:

.fooevents-copy-from-purchaser {
	float: right; 
	margin-bottom:-1.7em
}

If you are not using labels but rather input placeholders, please use the following code snippet:

.fooevents-copy-from-purchaser {
	float: right; 
	margin-top:-2em
}

Show the “Event Details” tab first on the event page #

Add the following code snippet to your theme’s functions.php file.

add_filter( 'woocommerce_product_tabs', 'reorder_tabs', 98 );
function reorder_tabs( $tabs ) {

    $tabs['woocommerce_events']['priority'] = 1; 
    return $tabs;

}

Direct all ‘Add to cart’ buttons to product pages #

If a product is a simple product, by default, the ‘Add to cart’ button will automatically add a product to the customer’s cart. When using the FooEvents Bookings extension, you may require that your customers first go to the product page to select the booking date and slot. The following snippet will ensure that when the ‘Add to cart’ button is clicked for simple products, the user will be directed to the product page.

add_filter( 'woocommerce_loop_add_to_cart_link', 'fooevents_modify_add_to_cart_button_url', 10, 2 );
function fooevents_modify_add_to_cart_button_url( $button, $product ) {
    if (is_product_category() || is_shop()) {
        $button_text = $product->add_to_cart_text();
        $button_link = $product->get_permalink();
        $button = '<a class="button" href="' . $button_link . '">' . $button_text . '</a>';
        return $button;
    }
}

Display FREE if the event price is set to zero (0) #

Add the following code snippet to your theme’s functions.php file if you want to change events and products with a price of “0” to “FREE”. You can also replace the word “FREE” with another word or phrase or leave it blank if you don’t want anything to display.

add_filter( 'woocommerce_get_price_html', 'wp_price_free_zero_empty', 100, 2 );
function wp_price_free_zero_empty( $price, $product ) {
	 if ( '' === $product->get_price() || 0 == $product->get_price() ) {
		$price = 'FREE';
	}
	return $price;
}

Display products and variations (tickets) in a table grid format #

Add the following code snippet to your theme’s functions.php file in order to display products and variations in a table grid format on the event/product page instead of the default drop-down list. Each ticket option will be listed in a new row and have its own quantity picker.

Please note: This code snippet is not compatible with the FooEvents Seating and FooEvents Bookings product page selectors.

/**
 * Display variations in a table format.
 */

function woocommerce_variable_add_to_cart() {

	global $product, $post;

	// Enter a comma separated list of product ID's that should display variations in table format. Leave empty to display all product ( e.g array() )
	$products = array( ); 

	if ( in_array( $post->ID, $products ) || empty( $products ) ) {

		$variations = find_valid_variations();

		// Check if the special 'price_grid' meta is set, if it is, load the default template.
		if ( get_post_meta( $post->ID, 'price_grid', true ) ) {

			// Enqueue variation scripts.
			wp_enqueue_script( 'wc-add-to-cart-variation' );

			// Load the template
			wc_get_template(
				'single-product/add-to-cart/variable.php',
				array(
					'available_variations' => $product->get_available_variations(),
					'attributes'           => $product->get_variation_attributes(),
					'selected_attributes'  => $product->get_variation_default_attributes(),
				)
			);

			return;
		}
		// Cool, lets do our own template!
		?>
			<table class="variations variations-grid" cellspacing="0">
				<tbody>

			<?php
			$variation = 0;
			foreach ( $variations as $key => $value ) {
				if ( ! $value['variation_is_visible'] ) {
					continue;
				}
				if ( $variation != $value['variation_id'] ) {

					?>

					<tr>
						<td>
						<?php

						foreach ( $value['attributes'] as $key => $val ) {
							$val = str_replace( array( '-', '_' ), ' ', $val );
							printf( '<div class="attr attr-%s">%s</div>', $key, ucwords( $val ) );
						}
						?>
						</td>
						<td>
						<?php echo $value['price_html']; ?>
						</td>

						<?php if ( $value['is_in_stock'] ) { ?>
							<form class="cart"  action="<?php echo esc_url( $product->add_to_cart_url() ); ?>" method="post" enctype='multipart/form-data'>
								<td id="variation_<?php echo $value['variation_id']; ?>">
									<?php woocommerce_quantity_input(); ?>
									<?php
									$variation_minimum_quantity  = get_post_meta( $value['variation_id'], 'variation_minimum_allowed_quantity', true );
									$variation_maximum_quantity  = get_post_meta( $value['variation_id'], 'variation_maximum_allowed_quantity', true );
									$variation_group_of_quantity = get_post_meta( $value['variation_id'], 'variation_group_of_quantity', true );
									?>
									<?php if ( isset( $variation_group_of_quantity ) ) { ?>
										<img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" data-wp-preserve="%3Cscript%3E%0A%09%09%09%09%09%09%09%09%09%09jQuery(document).ready(function(%24)%7B%0A%09%09%09%09%09%09%09%09%09%09%09%24(%20%22%23variation_%3C%3Fphp%20echo%20%24value%5B'variation_id'%5D%3B%20%3F%3E%20.qty%22%20).attr(%20%22step%22%2C%20%3C%3Fphp%20echo%20%24variation_group_of_quantity%3B%20%3F%3E%20)%3B%0A%09%09%09%09%09%09%09%09%09%09%09%24(%20%22%23variation_%3C%3Fphp%20echo%20%24value%5B'variation_id'%5D%3B%20%3F%3E%20.qty%22%20).attr(%20%22value%22%2C%20%3C%3Fphp%20echo%20%24variation_group_of_quantity%3B%20%3F%3E%20)%3B%0A%09%09%09%09%09%09%09%09%09%09%09%24(%20%22%23variation_%3C%3Fphp%20echo%20%24value%5B'variation_id'%5D%3B%20%3F%3E%20.qty%22%20).attr(%20%22min%22%2C%20%3C%3Fphp%20echo%20%24variation_minimum_quantity%3B%20%3F%3E%20)%3B%0A%09%09%09%09%09%09%09%09%09%09%09%24(%20%22%23variation_%3C%3Fphp%20echo%20%24value%5B'variation_id'%5D%3B%20%3F%3E%20.qty%22%20).attr(%20%22max%22%2C%20%3C%3Fphp%20echo%20%24variation_maximum_quantity%3B%20%3F%3E%20)%3B%0A%09%09%09%09%09%09%09%09%09%09%7D)%3B%0A%09%09%09%09%09%09%09%09%09%09%3C%2Fscript%3E" data-mce-resize="false" data-mce-placeholder="1" class="mce-object" width="20" height="20" alt="&lt;script&gt;" title="&lt;script&gt;" />									
									<?php } ?>
								</td>
								<td>
									<?php
									if ( ! empty( $value['attributes'] ) ) {
										foreach ( $value['attributes'] as $attr_key => $attr_value ) {
											?>
											<input type="hidden" name="<?php echo $attr_key; ?>" value="<?php echo $attr_value; ?>">
											<?php
										}
									}
									?>
									<button type="submit" class="single_add_to_cart_button btn btn-primary"><span class="glyphicon glyphicon-tag"></span> Add to cart</button>
								</td>
								<input type="hidden" name="variation_id" value="<?php echo $value['variation_id']; ?>" />
								<input type="hidden" name="product_id" value="<?php echo esc_attr( $post->ID ); ?>" />
								<input type="hidden" name="add-to-cart" value="<?php echo esc_attr( $post->ID ); ?>" />
							</form>
							<?php } else { ?>
								<td colspan="2">
									<p class="stock out-of-stock"><?php _e( 'This item is currently out of stock and unavailable.', 'woocommerce' ); ?></p>
								</td>
							<?php } ?>
					</tr>
					<?php
					$variation = $value['variation_id'];
				}
			}
			?>
			</tbody>
			</table>


		<?php
	} else {

		// Enqueue variation scripts.
		wp_enqueue_script( 'wc-add-to-cart-variation' );

		// Load the template
		wc_get_template(
			'single-product/add-to-cart/variable.php',
			array(
				'available_variations' => $product->get_available_variations(),
				'attributes'           => $product->get_variation_attributes(),
				'selected_attributes'  => $product->get_variation_default_attributes(),
			)
		);
		return;
	}
}

function find_valid_variations() {
	global $product, $post;

		$variations   = $product->get_available_variations();
		$attributes   = $product->get_attributes();
		$new_variants = array();

		// Loop through all variations
	foreach ( $variations as $variation ) {

		// Peruse the attributes.

		// 1. If both are explicitly set, this is a valid variation
		// 2. If one is not set, that means any, and we must 'create' the rest.

		$valid = true; // so far
		foreach ( $attributes as $slug => $args ) {
			if ( array_key_exists( "attribute_$slug", $variation['attributes'] ) && ! empty( $variation['attributes'][ "attribute_$slug" ] ) ) {
				// Exists

			} else {
				// Not exists, create
				$valid = false; // it contains 'anys'
				// loop through all options for the 'ANY' attribute, and add each
				foreach ( explode( '|', $attributes[ $slug ]['value'] ) as $attribute ) {
					$attribute                                      = trim( $attribute );
					$new_variant                                    = $variation;
					$new_variant['attributes'][ "attribute_$slug" ] = $attribute;
					$new_variants[]                                 = $new_variant;
				}
			}
		}

		// This contains ALL set attributes, and is itself a 'valid' variation.
		if ( $valid ) {

			$new_variants[] = $variation;
		}
	}

		return $new_variants;
}

Add support for daily start and end times to your ticket themes #

As of version 1.5.5 of the FooEvents Multi-day plugin, you can select different start and end times for each day of a multi-day event. Support for this feature has also been added to all FooEvents Ticket Themes. Please follow these instructions to update an existing ticket theme. If you are using a customized ticket theme and are not able to replace the ticket theme with the updated version, please add the following code snippet to your ticket theme in order to add support for start and end times.

<!-- MULTI-DAY DETAILS -->
										
<?php if ( $ticket['WooCommerceEventsTicketDisplayMultiDay'] == 'on' ) : ?>
	<?php $x = 1; ?>
	<?php $y = 0; ?>    
	<?php foreach ( $ticket['WooCommerceEventsSelectDate'] as $date ) : ?>
			<strong><?php printf( __( '%1$s %2$d: ', 'woocommerce-events' ), $ticket['dayTerm'], $x ); ?></strong>
			<?php echo esc_attr( $date ); ?><br /> 
			<?php if ( ! empty( $ticket['WooCommerceEventsSelectDateHour'][ $y ] ) && ! empty( $ticket['WooCommerceEventsSelectDateMinutes'][ $y ] ) ) : ?>
				<?php echo $ticket['WooCommerceEventsSelectDateHour'][ $y ] . ':' . $ticket['WooCommerceEventsSelectDateMinutes'][ $y ]; ?><?php echo( isset( $ticket['WooCommerceEventsSelectDatePeriod'][ $y ] ) ) ? ' ' . $ticket['WooCommerceEventsSelectDatePeriod'][ $y ] : ''; ?>
			<?php endif; ?>
			<?php if ( ! empty( $ticket['WooCommerceEventsSelectDateHourEnd'][ $y ] ) && ! empty( $ticket['WooCommerceEventsSelectDateMinutesEnd'][ $y ] ) ) : ?>
				<?php echo ' - ' . $ticket['WooCommerceEventsSelectDateHourEnd'][ $y ] . ':' . $ticket['WooCommerceEventsSelectDateMinutesEnd'][ $y ]; ?><?php echo( isset( $ticket['WooCommerceEventsSelectDatePeriodEnd'][ $y ] ) ) ? ' ' . $ticket['WooCommerceEventsSelectDatePeriodEnd'][ $y ] : ''; ?>
			<?php endif; ?>	
		<br />										
		<?php $x++; ?>
		<?php $y++; ?>
	<?php endforeach; ?>
<?php endif; ?>

The default WooCommerce Add to Cart buttons displayed on shop listing pages will automatically add a product to the cart and redirect to the cart page. When using FooEvents Bookings, you might prefer to channel the user through the product page so that they can first make a slot and time booking selection before proceeding to the cart page. The following snippet will replace the add-to-cart link with a link to the product page. This will ensure the user is able to make the appropriate booking selection on the product page before proceeding to the cart or checkout page.

/**
* @snippet Change WooCommerce ‘Add to Cart’ button to 'View Product'
* @source https://www.wptechnic.com/?p=4615
* @author Muhammad Tamzid
* @compatible WC 4.3.1
*/
// Change WooCommerce 'Add To Cart' button to 'View Product'
add_filter( 'woocommerce_loop_add_to_cart_link', 'wpt_custom_view_product_button', 10, 2 );
function wpt_custom_view_product_button( $button, $product ) {
    // Ignore for variable products
    if ( $product->is_type( 'variable' ) ) {
        return $button;
    }
    // Button text here
    $button_text = __( 'Book Ticket', 'woocommerce' );
    return '<a class="button wpt-custom-view-product-button" href="' . $product->get_permalink() . '">' . $button_text . '</a>';
}

Display the event date for “Single” events in the Cart and on the Checkout page #

add_filter( 'woocommerce_cart_item_name', 'add_event_date_cart_checkout', 10, 3 );
function add_event_date_cart_checkout( $product_name, $cart_item, $cart_item_key ) {
	$product = $cart_item['data'];

	if ( $value = $product->get_meta( 'WooCommerceEventsDate' ) ) {
		$product_name .= '<small>' . $value . '</small>';
	}
	return $product_name;
}

Articles

Tags , , , , , , , , , , , , , , , , , , ,