Top 5 Programming Questions and Answers Regarding WooCommerce Events and Calendar Part - 1

February 7, 2017,
Top 5 Programming Questions and Answers Regarding WooCommerce Events and Calendar Part - 1
Displaying the events on Google calendar is a right way to keep the audience up to date about upcoming events. But it is never easy to for programmers to use the right code to enable events calendar on WooCommerce website. FMEAddons has picked up this week’s hot questions and answers given by the top community developers. Theses answers have been taken from the community and not represents us. Let’s have look on 5 top questions and answers regarding WooCommerce calendar and events. Question No. 1 A user using WooCommerce have an issue regarding variable products. He wants to get information regarding current product variation by adding “found-variation” on events of variation form. He used this code but not working for him.
jQuery.fn.wc_variation_form.bind(
    'found_variation',
    function(event, variation) {
        console.log(variation); // logging to see the variation information
        $('#product-price').html(variation.price_html); // showing the variation price at custom html element
    }
);
Answer: Please use this code.
$(document).on( 'found_variation', 'form.cart', function( event, variation ) {
/* Your code */           
});
Question No. 2 A user has synced WooCommerce bookings with Google calendar to make easy for his employees to see the booking dates by customers for the trip. He wants to display product add-on in the description as it is showing resources and numbers of persons. He applied the code but got this error. Fatal error: Call to a member function get_order_item_totals() on a non-object in /home/content/12/10265512/html/wp-content/plugins/woocommerce-bookings/includes/integrations/class-wc-bookings-google-calendar-integration.php on line 454 He wants to get this system for him and his employees as he applied this code.
public function sync_booking( $booking_id ) {
    $event_id     = get_post_meta( $booking_id, '_wc_bookings_gcalendar_event_id', true );
    $booking      = get_wc_booking( $booking_id );
    $api_url      = $this->calendars_uri . $this->calendar_id . '/events';
    $access_token = $this->get_access_token();
    $timezone     = wc_booking_get_timezone_string();
    $product      = $booking->get_product();
    $summary      = '#' . $booking->id . ' - ' . $product->get_title();
    $description  = '';

    // Add resources in description

        if ( $resource = $booking->get_resource() ) {
        $description .= __( 'Resource #', 'woocommerce-bookings' ) . $resource->ID . ' - ' . $resource->post_title;
    }

    // Add ProductAdd on in description testing this 

  if ( $totals = $order->get_order_item_totals() ) {
            $i = 0;
            foreach ( $totals as $total ) {
                $i++;

                    if ( $i == 1 ) {

                    $description .= sprintf($total['label']) . PHP_EOL;
                    $description .= sprintf($total['value']) . PHP_EOL;
                }
            }
        }   


    // Add persons in description
    if ( $booking->has_persons() ) {
        $description .= ( '' != $description ) ? PHP_EOL . PHP_EOL : '';

        foreach ( $booking->get_persons() as $id => $qty ) {
            if ( 0 === $qty ) {
                continue;
            }

            $person_type = ( 0 < $id ) ? get_the_title( $id ) : __( 'Person(s)', 'woocommerce-bookings' );
            $description .= sprintf( __( '%s: %d', 'woocommerce-bookings'), $person_type, $qty ) . PHP_EOL;
            $description .= wp_kses_post( $product->post->post_excerpt, array() ) . PHP_EOL;
            $description .= sprintf("ADDITIONAL NOTES:") . PHP_EOL;
            $description .= sprintf("Hey John passing static notes to Calender test") . PHP_EOL;

        }
    }
Answer: Please pull all order from email-orders-table and use this code
// Add First Name of Guest
$description .= sprintf( __( 'NAME: %s', 'woocommerce-bookings' ), $booking->get_order()->billing_first_name ) . PHP_EOL;
// Add their email address
$description .= sprintf( __('EMAIL: %s', 'woocommerce-bookings'), $booking->get_order()->billing_email ) . PHP_EOL;
// Add their Phone Number
$description .= sprintf( __('PHONE: %s', 'woocommerce-bookings'), $booking->get_order()->billing_phone ) . PHP_EOL;
// Purchase Notes and WooCommerce Product Add Ons
$description .= sprintf("ADDITIONAL NOTES:") . PHP_EOL;
$description .= sprintf ( __('%s', 'woocommerce-bookings'), strip_tags($order->email_order_items_table( $order->is_download_permitted(), true, true ))) . PHP_EOL ;
This code works perfectly after stripping HTML tags and display guest information to all the staff in private Google calendar. Question No. 3   A user has working on local feed that should display WooCommerce booking but get this error and need a solution. Lines not delimited by CRLF sequence near line # 1 Reference: RFC 5545 3.1. Content Lines He has applied this code.
php

// - start collecting output -
ob_start();

// - file header -
header('Content-type: text/calendar');
header('Content-Disposition: attachment; filename="ical.ics"');
?>
BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//bobbin v0.1//NONSGML iCal Writer//EN
CALSCALE:GREGORIAN
METHOD:PUBLISH
php
global $wpdb, $woocommerce, $post, $feed;

$orders = $feed->get_bookings();

foreach ($orders as $o):

    $order = new WC_Order($o->ID);
    $items = $order->get_items();
    foreach ($items as $id => $item) {
        $length = $item['item_meta']["Aantal uur (€25,00)"][0];
        $item['item_meta'] = $wpdb->get_results('SELECT * FROM wp_woocommerce_order_itemmeta WHERE order_item_id='.$id, 'ARRAY_A');
        foreach ($item['item_meta'] as $meta) {
            $item['item_meta'][$meta['meta_key']] = $meta['meta_value'];
        }

        if (isset($item['item_meta']['Verhuur datum'])) {



        // var_dump($item['item_meta']);

            $date = $item['item_meta']['Verhuur datum'];
            $start = $item['item_meta']['Booking Time'];
            $length = $item['item_meta']["Aantal uur (€25,00)"];
            $starttime = date('Ymd\THis', strtotime($date . " " . $start));
            $endtime = date('Ymd\THis', strtotime($date . " " . $start) + $length * 3600);

// - content header -
?>
BEGIN:VEVENT
DTSTART:php echo $starttime . "\n\r"; ?>
DTEND:php echo $endtime . "\n\r"; ?>
DTSTAMP:php echo date('Ymd\THis', strtotime($o->post_date)) . "\n\r"; ?>
UID:php echo $o->ID; ?>@se-haaglanden.nl
CREATED:php echo date('Ymd\THis', strtotime($o->post_date)) . "\n\r"; ?>
DESCRIPTION:php echo $o->post_title . "\n\r"; ?>
LAST-MODIFIED:php date('Ymd\THis', strtotime($o->post_modified)) . "\n\r"; ?>
SEQUENCE:0
STATUS:CONFIRMED
SUMMARY:php echo $o->post_title . "\n\r"; ?>
TRANSP:OPAQUE
END:VEVENT
php } } endforeach; ?>
END:VCALENDAR
php exit; ?>
Answer: Your editor is ending with simple LF and not with CRLF. Please add this code    to each buffer line and do it like this.
BEGIN:VCALENDARphp echo "\r\n" ?>
VERSION:2.0php echo "\r\n" ?>
Question No. 4 A user has a marketplace like a website where users get registered as a vendor. He wants to develop a code which automatically creates the product with the following specs after user signs up.
Product name = Booking - the_author_meta ('display_name') Product slug = calendar-the_author_meta ('user_login')
Answer: A WooCommerce core handles user registration so you have to hook  user_register to achieve this and run this hook right when users signed up. And use this wp_insert_post to insert post with post_type = product to create the product Use this code
add_action( 'user_register', 'myCustomProduct', 10, 1 );

function myCustomProduct($user_id)
{
    $user_info = get_userdata($user_id);
    $display_name = $user_info->display_name;

    $user_full_name = get_user_meta($user_id, 'first_name', TRUE) . ' ' . get_user_meta($user_id, 'last_name', TRUE);

    $my_product_name = 'Booking - ' . trim($user_full_name);
    $my_slug = 'calendar-' . str_replace(array(' '), '', strip_tags($display_name));

    $post = array(
        'post_author' => $user_id,
        'post_content' => '',
        'post_status' => "publish",
        'post_title' => wp_strip_all_tags($my_product_name),
        'post_name'=> $my_slug,
        'post_parent' => '',
        'post_type' => "product",
    );

    //Create Post
    $post_id = wp_insert_post($post, $wp_error);

    //set Product Category
    //wp_set_object_terms( $post_id, 'Your Category Name ', 'product_cat' );
    //set product type
    wp_set_object_terms($post_id, 'simple', 'product_type');

    update_post_meta($post_id, '_visibility', 'visible');
    update_post_meta($post_id, '_stock_status', 'instock');
    update_post_meta($post_id, 'total_sales', '0');
    update_post_meta($post_id, '_sku', "");
    update_post_meta($post_id, '_product_attributes', array());
    update_post_meta($post_id, '_manage_stock', "no");
    update_post_meta($post_id, '_backorders', "no");
    update_post_meta($post_id, '_stock', "");
    //update_post_meta($post_id, '_downloadable', 'yes');
    //update_post_meta($post_id, '_virtual', 'yes');
    //update_post_meta($post_id, '_regular_price', "1");
    //update_post_meta($post_id, '_sale_price', "1");
    //update_post_meta($post_id, '_purchase_note', "");
    //update_post_meta($post_id, '_featured', "no");
    //update_post_meta($post_id, '_weight', "");
    //update_post_meta($post_id, '_length', "");
    //update_post_meta($post_id, '_width', "");
    //update_post_meta($post_id, '_height', "");
    //update_post_meta($post_id, '_sale_price_dates_from', "");
    //update_post_meta($post_id, '_sale_price_dates_to', "");
    //update_post_meta($post_id, '_price', "1");
    //update_post_meta($post_id, '_sold_individually', "");
}
Question 5   A user has contact form 7 having two drops down menus to order events tickets without registration. But it doesn’t save the data provided by customers during order which makes difficult to track the orders of customers. He used this code
on_sent_ok: "switch(document.forms[0].elements["registration_type"].value){case "Normal Registration": location.replace('url/checkout-3/?clear-cart&add-to-cart=325&quantity=1');break;case "Presenter Registration": location.replace('url/checkout-3/?clear-cart&add-to-cart=327&quantity=1');break;};"
Answer: You can save the contact form 7 data in session and if you want to save them later you have to consider that order is not created at that point. Use this action the wpcf7_mail_sent that triggered when email is sent. These codes should take place in your theme function.php file.
function wc_wpcf7_mail_sent_function($contact_form) {
    $submission = WPCF7_Submission::get_instance();
    if($submission) {
        $posted_data = $submission->get_posted_data();
        WC()->session->set('cf7_posted_data', $posted_data);
    }
}
add_action('wpcf7_mail_sent', 'wc_wpcf7_mail_sent_function'); 
This code uses WC-session and save the data in custom fields when the order is processed.
function wc_save_cf7_data_to_order($order_id) {
    $posted_data = base64_encode(serialize(WC()->session->get('cf7_posted_data')));
    if(!empty($posted_data)) {
        add_post_meta($order_id, 'cf7_posted_data', $posted_data);
        WC()->session->__unset('cf7_posted_data');
    }
}
add_action('woocommerce_checkout_order_processed', 'wc_save_cf7_data_to_order', 10, 1);
This code will save all the data in the CF7 form in serialized string and stored in base64 to avoid decoding error. At last, you have to add the meta box to show CF7 data on order page.
function wc_add_meta_box() {
    add_meta_box(
        'order_tickets',
        __('Contact form data', 'your-theme'),
        'wc_print_order_cf7_data_callback'),
        'shop_order'
    );
}
add_action('add_meta_boxes', 'wc_add_meta_box');
Then show data by using this
public function print_order_tickets_callback($post) {
    $posted_data = get_post_meta($post->ID, 'cf7_posted_data', true);
    if(!empty($tickets)) {
        $posted_data = unserialiaze(base64_decode($posted_data));
        foreach($posted_data as $key => $data) {
            echo '', $key, ' :  ', $data, '
'
; } } }

Download WooCommerce Events and Calendar Plugin 

woo-com-event-manager