ACF Google Maps – Ways to output and format the Address in text form.

You can use Advanced Custom Fields to do some pretty cool things with Google Maps. But often you would want to spit out the address from the map in a formatted form. Here are some examples:

Simplest form:

“111 My Road, City, ST, United States”

// Get your field
$address = get_field('address');
// Get the Address String
echo $address['address'];

Strip the “, United States”

“111 My Road, City, ST”

// Get your field
$address = get_field('address');
// Get the Address String
$location = $address['address'];
// Find the "US" at the end of the string
$us = ', United States';
// And drop if from the Address
$trimmedAdd = str_replace($us, '', $location);
// spit it out
echo $trimmedAdd;

Strip the “, United States” and add a break making it multiline

” 111 My Road
City, ST ”

// Get your field
$address = get_field('address');
// Get the Address String
$location = $address['address'];
// Find the first comma and replace it with a break
$string = strpos($location,',');
if ($pos !== false) {
	$newstring = substr_replace($location,'<br>',$string,strlen(','));
}
// Find the "US" at the end of the string
$us = ', United States';
// And drop if from the Address
$trimmedAdd = str_replace($us, '', $newstring);
// spit it out
echo $trimmedAdd;

 

ACF Reverse Query on a Post Object

This is a slider from the index.php pulling the testimonials

<?php 
// Let's get in homepage mode.
$post = get_post(505); // My home "page" id = 505
setup_postdata( $post );
/*
	Reverse Query on the Post Object Field 
*/
$testimonials = get_posts(array(
	'post_type' => 'testimonial',
	'meta_query' => array(
		array(
			'key' => 'pages_to_show_testimonial', // name of custom field
			'value' => '"' . get_the_ID() . '"', // matches exaclty "123", 
			'compare' => 'LIKE'
		)
	)
));
// now get out of homepage mode now that we have our testimonials.
wp_reset_postdata();
if( $testimonials ): ?>
<div class="wrapper">
    <div class="testimonial">
    	<ul class="slides">
			<?php foreach( $testimonials as $testimonial ): 
            // get those id's for the fields
			 $ID = $testimonial->ID;
            $job_title = get_field( 'job_title', $ID ); 
            $company = get_field( 'company', $ID ); 
            $testimonial = get_field( 'testimonial', $ID); 
            $title = get_the_title($ID); 
            ?>
            
                <li> 
                	<div class="the-testimonial"><?php echo $testimonial; ?></div>
                	<div class="the-testimonial-name"><?php echo $title; ?></div>
                	<?php if($job_title != '' ) { echo '<div class="the-testimonial-jt">, '.$job_title.'</div>'; }?>
                	<?php if($company != '' ) { echo '<div class="the-testimonial-company">, '.$company.'</div>'; }?>  
                </li>
            
            <?php endforeach; ?>
        </ul><!-- slides -->
    </div><!-- .testimonial -->
</div><!-- wrapper -->
<?php endif; wp_reset_postdata(); ?>

 

Sortable Admin Columns with Advanced Custom Fields ACF

Add Advanced Custom Fields ACF to your admin columns in WordPress and be able to sort them.

For this I will add a custom thumbnail and Event start date for an “Event” Custom post type.

First, you need two functions. One to create the columns, overriding what was default in WordPress and one to tell what each column to do.

/*-------------------------------------------------------------------------------
	Custom Columns
-------------------------------------------------------------------------------*/

function my_page_columns($columns)
{
	$columns = array(
		'cb' 	=> '<input type="checkbox" />',
                'title' 	=> 'Title',
		'thumbnail'	=> 'Thumbnail',
		'event' 	=> 'Event Date',
		//'author'	=> 'Author',
		//'date'	=> 'Date',
	);
	return $columns;
}

function my_custom_columns($column)
{
	global $post;
	if($column == 'event')
	{
	   $date = DateTime::createFromFormat('Ymd', get_field('event_date'));
	   if( empty( $date ) ) :
	     echo 'No Date';
	   else:
	     echo $date->format('M/d/Y');
	   endif;

	} elseif ($column == 'thumbnail'){
	   $image = get_field('event_image');
	   $size = 'thumbnail';
	   $thumb = $image['sizes'][ $size ];
	   echo '<img src="'.$thumb.'" />';
	}
}

add_action("manage_event_posts_custom_column", "my_custom_columns");
add_filter("manage_edit-event_columns", "my_page_columns");

It’s important to note that the structure of the add_action: ¬†‘manage_{YOUR_POSTTYPE}_posts_custom_column’
and the structure of the filter ‘manage_edit-{YOUR_POSTTYPE}_columns’

Then this final function to sort by Event Date:

function my_column_register_sortable( $columns )
{
	$columns['event'] = 'event';
	return $columns;
}

add_filter("manage_edit-event_sortable_columns", "my_column_register_sortable" );

Again, note the structure of the filter:
‘manage_edit-{YOUR_POSTTYPE}_event_sortable_columns’

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="" />';
		}   ?>