Add Custom Checkout fields to Woocommerce

Here are a couple sample fields you can add to your theme’s functions file to create some Custom Fields on checkout for Woocommerce.

First, add the fields to checkout. There is also a conditional Birthday field…

/**
 * Add the field to the checkout
 */
add_action( 'woocommerce_after_order_notes', 'my_custom_checkout_field' );

function my_custom_checkout_field( $checkout ) {

	// Student Name
    echo '<div id="my_custom_checkout_field"><h2>' . __('Student Name / Student Teacher') . '</h2>';

    woocommerce_form_field( 'student_name', array(
        'type'          => 'text',
        'class'         => array('my-field-class form-row-wide'),
        'label'         => __('Student Name'),
        'placeholder'   => __('Student Name'),
		'required'      => true,
        ), $checkout->get_value( 'student_name' ));

   // Teacher Name

    woocommerce_form_field( 'student_teacher', array(
        'type'          => 'text',
        'class'         => array('my-field-class form-row-wide'),
        'label'         => __('Student Teacher'),
        'placeholder'   => __('Student Teacher'),
		'required'      => true,
        ), $checkout->get_value( 'student_teacher' ));
	
	// Grade
		
		 woocommerce_form_field( 'grade', array(
        'type'          => 'text',
        'class'         => array('my-field-class form-row-wide'),
        'label'         => __('Grade'),
        'placeholder'   => __('Grade'),
		'required'      => true,
        ), $checkout->get_value( 'grade' ));

    echo '</div>';
	
	
		// If in Birthday Book Category...	
		//Check if Book in Cart (UPDATE WITH YOUR PRODUCT ID)
		$book_in_cart = wordimpress_is_conditional_product_in_cart( 3702 );
		
		if ( $book_in_cart === true ) {
		  	woocommerce_form_field( 'child_birthday', array(
				'type'          => 'text',
				'class'         => array('my-field-class form-row-wide'),
				'label'         => __('Child\'s Birthday'),
				'placeholder'   => __('mm/dd/yyyy'),
				'required'      => true,
				), $checkout->get_value( 'child_birthday' ));
		} 

}

For the Birthday, check to see if it’s in the cart…

/**
 * Check if Conditional Product is In cart
 *
 * @param $product_id
 *
 * @return bool
 */
function wordimpress_is_conditional_product_in_cart( $product_id ) {
	//Check to see if user has product in cart
	global $woocommerce;
 
	//flag no book in cart
	$book_in_cart = false;
 
	foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $values ) {
		$_product = $values['data'];
 
		if ( $_product->id === $product_id ) {
			//book is in cart!
			$book_in_cart = true;
 
		}
	}
 
	return $book_in_cart;
 
}

Process the checkout…

/**
 * Process the checkout
 */
add_action('woocommerce_checkout_process', 'my_custom_checkout_field_process');

function my_custom_checkout_field_process() {
    // Check if set, if its not set add an error.
    if ( ! $_POST['student_name'] )
        wc_add_notice( __( '<strong>Student\'s name</strong> is a required field.' ), 'error' );
	if ( ! $_POST['student_teacher'] )
        wc_add_notice( __( '<strong>Teachers\'s name</strong> is a required field.' ), 'error' );
	if ( ! $_POST['grade'] )
        wc_add_notice( __( '<strong>Grade</strong> is a required field.' ), 'error' );
}

Save those fields!

/**
 * Save the fields
 */
add_action( 'woocommerce_checkout_update_order_meta', 'my_custom_checkout_field_update_order_meta' );

function my_custom_checkout_field_update_order_meta( $order_id ) {
    if ( ! empty( $_POST['student_name'] ) ) {
        update_post_meta( $order_id, 'Student Name', sanitize_text_field( $_POST['student_name'] ) );
    }
	if ( ! empty( $_POST['student_teacher'] ) ) {
        update_post_meta( $order_id, 'Student Teacher', sanitize_text_field( $_POST['student_teacher'] ) );
    }
	if ( ! empty( $_POST['grade'] ) ) {
        update_post_meta( $order_id, 'Grade', sanitize_text_field( $_POST['grade'] ) );
    }
	if ( ! empty( $_POST['child_birthday'] ) ) {
        update_post_meta( $order_id, 'Child Birthday', sanitize_text_field( $_POST['child_birthday'] ) );
    }
}

Finally, display those fields on the order backend edit page…

/**
 * Display field value on the order edit page
 */
add_action( 'woocommerce_admin_order_data_after_billing_address', 'my_custom_checkout_field_display_admin_order_meta', 10, 1 );

function my_custom_checkout_field_display_admin_order_meta($order){
    echo '<p><strong>'.__('Student Name').':</strong> ' . get_post_meta( $order->id, 'Student Name', true ) . '</p>';
	echo '<p><strong>'.__('Student Teacher').':</strong> ' . get_post_meta( $order->id, 'Student Teacher', true ) . '</p>';
	echo '<p><strong>'.__('Grade').':</strong> ' . get_post_meta( $order->id, 'Grade', true ) . '</p>';
	echo '<p><strong>'.__('Child Birthday').':</strong> ' . get_post_meta( $order->id, 'Child Birthday', true ) . '</p>';
}

Bonus: Add those fields that go out in the email to the store owner…

In “admin-new-order.php” in the Woocommerce email template file, and after the do_action(‘woocommerce_email_customer_details’)

<p><strong><?php _e( 'Student\'s Name:', 'woocommerce' ); ?></strong> <?php echo get_post_meta( $order->id, 'Student Name', true ) ?></p>
<p><strong><?php _e( 'Teacher\'s Name:', 'woocommerce' ); ?></strong> <?php echo get_post_meta( $order->id, 'Teacher Name', true ) ?></p>
<p><strong><?php _e( 'Grade:', 'woocommerce' ); ?></strong> <?php echo get_post_meta( $order->id, 'Grade', true ) ?></p>

<?php if ( $order->child_birthday ) : ?>
	<p><strong><?php _e( 'Child Birthday:', 'woocommerce' ); ?></strong> <?php echo $order->child_birthday; ?></p>
<?php endif; ?>

 

Custom Social Media Share buttons

This is incomplete. You will need some css for your images and change a couple things in the code below, like the facebook app id to make this all work

	
	// Post Url
	$permalink = get_permalink();
	// Short Link for Twitter
	$shortlink = wp_get_shortlink();
	// Post title
	$title = get_the_title();
	// Description
	$excerpt = get_the_excerpt();
	// Featured Image
	$thumb_id = get_post_thumbnail_id();
	// Large Image
	$image_large_url_array = wp_get_attachment_image_src($thumb_id, 'large', true);
	$image_large_url = $image_large_url_array[0];
	// Thumb Image
	//$thumb_url_array = wp_get_attachment_image_src($thumb_id, 'thumbnail', true);
	//$thumb_url = $thumb_url_array[0];
	
	/* 
		Facebook
	______________________ */
	// Url of app created on Facebook
	$Furl = 'https://www.facebook.com/dialog/feed?app_id=1904914583066977';
	// Picture
	$picture = '&picture=' . $image_large_url;
	// title
	$name = '&name=' . $title;
	// Description
	$desc = '&description=' . $excerpt;
	// Redirect uri
	$redirect = '&redirect_uri=' . $permalink;
	// All together now...
	$facebook = $Furl . $picture . $name . $desc . $redirect;
	/* 
		Twitter
	______________________ */
	// Tweet Url
	$Turl = 'https://twitter.com/intent/tweet?';
	// Text
	$text = 'text=' . get_the_title();
	$postLink = '&url=' . $shortlink;
	$referer = '&original_referer=' . $permalink;
	// All together now...
	$twitter = $Turl . $text . $postLink . $referer;
	/* 
		Pintrest
	______________________ */
	$Purl = 'http://pinterest.com/pin/create/button/?url=' . $permalink;
	// Picture
	$Ptitle = '&description=' . $title;
	$media = '&media=' . $image_large_url;
	// All together now...
	$pintrest = $Purl . $media . $Ptitle . ' - My Beautiful Adventures';

and the html

<div id="share">
    <ul>
        <li class="facebook"><a href="<?php echo $facebook; ?>">Share on Facebook</a></li>
        <li class="twitter"><a href="<?php echo $twitter; ?>" target="_blank" data-related="AERIN">Tweet on Twitter</a></li>
        <li class="pintrest"><a href="<?php echo $pintrest; ?>" target="_blank">Pin on Pintrest</a></li>
    </ul>
</div><!-- share -->

 

Add to iCal gives wrong time

Add to iCal in Event Espresso adds the wrong time to iCal. Could be due to your timezone setting. By default WordPress is set to UTC, ‘Universal Time’. In my opinion you should leave it at this and any scripts or plugins you write can be amended with the local timestamp which you can use like:

$local_timestamp = get_the_time('U');

But to solve the original issue with Event Espresso iCal error if you timezone was left to default, you need to change the end of the timestamp in the iCal form. In, “(plugins) EE/modules/ical/EED_Ical.module.php” you can change the line on line 27 from;

const iCal_datetime_format = 'Ymd\THis\Z';

to

const iCal_datetime_format = 'Ymd\THis';

 

Catch that Image

Function that will look for the featured image first, then if no featured image it will look for the first image in the post, then if no image in the post it will show the default.png in your theme’s images folder. (you have to put the default.png in your theme of course.)

Functions File:

/*-------------------------------------
	Fallback for no featured image. 
	Will grab first image in post.
---------------------------------------*/
function catch_that_image() {
global $post, $posts;
$first_img = '';
ob_start();
ob_end_clean();
if(preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches)){
$first_img = $matches [1] [0];
return $first_img;
}
else {
$first_img = get_template_directory_uri()."/images/default.png";
return $first_img;
}
}

 

Theme File:

<?php if ( has_post_thumbnail()  ) {
		  the_post_thumbnail('large');
		} else {
		   echo '<img src="';
			 echo catch_that_image();
			 echo '" alt="" />';
		}   ?>

 

Open Colorbox for Newsletter signup on first web visit

Opens the first time, then leaves a cookie not to open for 15 more days.

the Javascript:

jQuery(document).ready(function ($) {
	
 if (document.cookie.indexOf('visited=true') == -1) {
        var fifteenDays = 1000*60*60*24*15;
        var expires = new Date((new Date()).valueOf() + fifteenDays);
        document.cookie = "visited=true;expires=" + expires.toUTCString();
        $.colorbox({width:"40%", inline:true, href:"#mc_form_pop"});
    }
});

 

Sample Portfolio page using Colorbox inline content

Sample WordPress portfolio page utilizing, Isotope jQuery plugin and it’s filtering system, and Colorbox to show inline content that features a gallery.

<?php
/**
 * Template Name: Portfolio
 */

get_header(); ?>

	<div id="primary" class="">
		<div id="content" role="main">

<?php 
		
		$customPostType = 'portfolio';
		if( is_page(16) ) { // portfolio
       		$customTax = 'room_type';
		} else {
			$customTax = 'project';
		}
		$wp_query = new WP_Query();
		$wp_query->query(array(
	   'post_type'=> $customPostType,
	   'posts_per_page' => -1,
	   'paged' => $paged,
));
	if ($wp_query->have_posts()) :  ?>
    <div class="wrapper">
    <div id="the-filters">
    <div class="filter">
    	Filter By: 
        <?php if( is_page(16) ) { // portfolio
			$current = 'current';
		} else {
			$current = '';
		} ?>
        <li><a href="<?php bloginfo('url'); ?>/portfolio/">Room</a></li> 
    	 <li><a href="<?php bloginfo('url'); ?>/portfolio/projects/">Project</a></li>
    </div><!-- flilter -->
    
    <div class="clear"></div>
    
    <?php 
	
	// Create Filter buttons from all Categories that have posts 
		
		// create an array
		$filterLinks = array();
		// an empty array to add to our previous array
		$newarray = array();
		// Starter "Show All' Array
		$starter = array('name'=>'All','slug'=>'*', 'class'=> 'is-checked');
		// put it into our array
		$filterLinks[] = $starter;
		
		 $taxterms = get_terms( $customTax );
		 // loop through terms if not empty
		 if ( ! empty( $taxterms ) && ! is_wp_error( $taxterms ) ){
		
			 foreach ( $taxterms as $taxterm ) {
			  	// show all is a little different, so we add a "." to the others
				$datafilter = '.' . $taxterm->slug;
				// create some 
				  $newarray = array(
						'name' => $taxterm->name,
						'slug' => $datafilter,
						'class' => ''
				  );
				 // load it up 
				  $filterLinks[] = $newarray;
				
			 } // endforeach
			
		 } // if not empty 
		 
    // Filter Buttons output
	echo '<div id="filters" class="button-group">' ."\n";
	// Create filter buttons from terms
		foreach ($filterLinks as $links) {
			echo '<button class="button '.$links['class'].'" data-filter="' . $links['slug'] . '">' . $links['name'] . '</button>'."\n";
		}
	echo '</div><!-- isotope filters --></div><!-- the filters --></div><!-- wrapper -->';
?> 
		
<div id="container" class="theportfolio">

<?php while ($wp_query->have_posts()) : ?>
<?php $wp_query->the_post(); 

	$portTitle = get_the_title(); 
	$portDesc = get_the_content();
	$saniTitle = sanitize_title($portTitle);
	$saniTitle = str_replace('-', '_', $saniTitle);
?>
	
<?php
// Get the terms with each post
$terms = get_the_terms( $post->ID, $customTax );
						
if ( $terms && ! is_wp_error( $terms ) ) : 

	$cat_links = array();

	foreach ( $terms as $term ) {
		$cat_links[] = $term->slug;
	}
						
	$mycats = join( " ", $cat_links );
?>


<?php endif; ?>

<?php if ( has_post_thumbnail() ) { ?>
    <div class="item portfolio <?php echo $mycats; ?>">
       <?php the_post_thumbnail('portfolio-three'); ?>
					
            <div class="portfolio-hover">
                <a  href="#" id="<?php echo $saniTitle ?>" >
                    <h2><?php the_title(); ?></h2>
                    <div class="clear"></div>
                   <h3>
                   <?php 
				   			$terms = get_the_terms( $post->ID, 'room_type' );
							$draught_links = array();

							foreach ( $terms as $term ) {
								$draught_links[] = $term->name;
							}
												
							$on_draught = join( ", ", $draught_links );
				  			
							 echo $on_draught; ?>
                   </h3>
                 </a>
             </div><!-- portfolio-hover -->
             
            
<div style='display:none'>   
<?php   
	/*-----------------------------------------------
  
  			Run the Repeater for the Gallery
   
  -----------------------------------------------*/
  if( have_rows('gallery') ): 
  	 while ( have_rows('gallery') ) :  the_row(); 
	 
        // Get field Name
       		$image = get_sub_field('image'); 
			$url = $image['url'];
			$title = $image['title'];
			$alt = $image['alt'];
			$size = 'portsingle';
			$sizeLarge = 'large';
			$thumb = $image['sizes'][ $size ];
			$large = $image['sizes'][ $sizeLarge ];
		 
		 
		 ?>
         
        <div  class="portopen inline_<?php echo $saniTitle ?>">
                
                <div class="portopentitle">
                	<h2><?php echo $portTitle; ?></h2>
                </div><!-- portopentitle -->
                
                 <div class="portopen-img-center">
                     <div class="portopen-img">
                        <img src="<?php echo $thumb; ?>" alt="<?php echo $alt; ?>" title="<?php echo $title; ?>"  />
                     </div><!-- port open img -->
                 </div><!-- port open img center -->
                 
					 <?php if( $portDesc != '' ) : ?>
                         <div class="galler-description">
                         		<div class="galler-description-pad">
                            		<?php echo $portDesc; ?>
                         		</div><!-- gal desc -->
                         </div><!-- gal desc -->
                     <?php endif; ?>
                </div><!-- anchored div -->
           
        
        <?php endwhile; endif; // repeater ?>
         </div><!-- display none -->
         
         
    </div><!-- item -->
    <?php } ?>
    
<script type="text/javascript">

</script>
    
    <?php endwhile; ?>
    
    
    
    </div><!-- container -->
    
    
    
  <?php //echo do_shortcode('[ajax_load_more post_type="portfolio" pause="true" scroll="false"]'); ?>
    
    <?php endif; ?>

		</div><!-- #content -->
	</div><!-- #primary -->

<?php //get_sidebar('portfolio'); ?>
 <script type="text/javascript">

jQuery(document).ready(function ($) { 

 <?php while ($wp_query->have_posts()) : ?>
<?php $wp_query->the_post(); 

	$portTitle = get_the_title(); 
	$portDesc = get_the_content();
	$saniTitle = sanitize_title($portTitle);
	$saniTitle = str_replace('-', '_', $saniTitle);
?>            
                var $<?php echo $saniTitle; ?>group = $('.inline_<?php echo $saniTitle; ?>').colorbox({
					   inline:true, 
					    width: '100%',
						innerWidth:'100%', 
						innerHeight:'100%'	,				   
						rel:'inline_<?php echo $saniTitle; ?>',
					   href: function(){
						return $(this).children();
				  }});
				   
				   $('#<?php echo $saniTitle; ?>').on('click', function(e){
						e.preventDefault();
						$<?php echo $saniTitle; ?>group.eq(0).click();
				  });
				  
				  <?php endwhile; ?>
});// END #####################################    END
</script>

<?php get_footer(); ?>

 

Custom Social Media Share Buttons for WordPress

This code gives you a little more control on how a post is shared with different social media services. This covers Facebook, Twitter and Pintrest. Gives a large featured image for Facebook and Title and Description and returns back to your page, short url for Twitter and Title for Twitter, and Large image for Pintrest with Post Title and a little extra description for you to customize. (image sprite not included. relies on css for social media icons.)

You will also need to go get your own Facebook App Id and replace the “you_need_your_own_app_id” (on line 24)

 <?php 
	
	// Post Url
	$permalink = get_permalink();
	// Short Link for Twitter
	$shortlink = wp_get_shortlink();
	// Post title
	$title = get_the_title();
	// Description
	$excerpt = get_the_excerpt();
	// Featured Image
	$thumb_id = get_post_thumbnail_id();
	// Large Image
	$image_large_url_array = wp_get_attachment_image_src($thumb_id, 'large', true);
	$image_large_url = $image_large_url_array[0];
	// Thumb Image
	//$thumb_url_array = wp_get_attachment_image_src($thumb_id, 'thumbnail', true);
	//$thumb_url = $thumb_url_array[0];
	
	/* 
		Facebook
	______________________ */
	// Url of app created on Facebook
	$Furl = 'https://www.facebook.com/dialog/feed?app_id=you_need_your_own_app_id';
	// Picture
	$picture = '&picture=' . $image_large_url;
	// title
	$name = '&name=' . $title;
	// Description
	$desc = '&description=' . $excerpt;
	// Redirect uri
	$redirect = '&redirect_uri=' . $permalink;
	// All together now...
	$facebook = $Furl . $picture . $name . $desc . $redirect;
	/* 
		Twitter
	______________________ */
	// Tweet Url
	$Turl = 'https://twitter.com/intent/tweet?';
	// Text
	$text = 'text=' . get_the_title();
	$postLink = '&url=' . $shortlink;
	$referer = '&original_referer=' . $permalink;
	// All together now...
	$twitter = $Turl . $text . $postLink . $referer;
	/* 
		Pintrest
	______________________ */
	$Purl = 'http://pinterest.com/pin/create/button/?url=' . $permalink;
	// Picture
	$Ptitle = '&description=' . $title;
	$media = '&media=' . $image_large_url;
	// All together now...
	$pintrest = $Purl . $media . $Ptitle . ' - Custom Pintrest Description';
	
	
	?>
<div id="share">
    <ul>
        <li class="facebook"><a href="<?php echo $facebook; ?>">Share on Facebook</a></li>
        <li class="twitter"><a href="<?php echo $twitter; ?>" target="_blank" data-related="AERIN">Tweet on Twitter</a></li>
        <li class="pintrest"><a href="<?php echo $pintrest; ?>" target="_blank">Pin on Pintrest</a></li>
    </ul>
</div><!-- share -->