Archive

Posts Tagged ‘shortcodes’

Creating Nifty Petitions Inside Your Posts

October 18th, 2012 Comments off

WordPress is a great multi-purpose platform. You can create many websites with many different purposes: a corporate website, a photography showcase, a news portal, a restaurant website with interactive menus… Oh, and blogs, of course. You can blog with WordPress. Forgot about that.

Strangely, non-profit organizations tend to overlook this flexibility and take advantage of it. In this tutorial, we’re going to show how to create a simple petition script to demonstrate how an organization can benefit from WordPress.

/>

What Are We Building, Exactly?

I’m a huge fan of shortcodes (as you can see from my previous posts), so we’re going to make a bunch of shortcodes and some helpful functions for the shortcodes to use. We’re going to get all of these together in a file called petition.php and use it as a WordPress plugin.

/>

Helper Functions

Since we’re going to use them inside our shortcodes, I thought it would be better to create and explain them first.

A Basic E-Mail Validating Function

If you’re using PHP5 on your server, we’re going to use the built-in e-mail validators for our function:

// e-mail address validating function
function validate_email( $email ) 
	if ( $email == '' ) 
		return false;
	 else 
		return filter_var( $email, FILTER_VALIDATE_EMAIL );
	
}

And if you’re using something ancient like PHP4, you can use a different function which makes use of regular expressions:

// e-mail address validating function
function validate_email( $email ) 
	if ( $email == '' ) 
		return false;
	 else 
		$eregi = preg_replace( '/([a-z0-9_.-]+)' . '@' . '([a-z0-9.-]+)2,255' . '.' . '([a-z]+)2,10/i', '', $email );
	}
	return empty( $eregi ) ? true : false;
}

Please Note: You can’t use both!

The Function to Submit the Entries

We could create and use a different database table to contain the petitions’ submissions but I don’t think that it’s a good practice. And hey, what’s wrong with custom fields?

// submit the signer with a 'petition_submission' meta key to the post
function submission( $name, $email, $date ) 
	global $post;
	$array = array( 'name' => $name, 'email' => $email, 'date' => $date );
	$petition_meta = serialize( $array );
	add_post_meta( $post->ID, 'petition_submission', $petition_meta );
	return true;

As you can read from the code;

  • We took the $name, $email and $date variables into the function (from the shortcode which we’ll get to in a minute)
  • Put the three variables together by creating an array and serializing it
  • And saved the data as a custom field named 'petition_submission'

Simple, right? Now we can get to the kinda-hard part.

The Function to Fetch the Submissions

We can now save the submissions but how will we get them and do stuff with them? Here’s how:

// fetch the submissions from the post
function get_the_submissions( $number = 5 ) 
	$petition_meta = get_post_custom_values( 'petition_submission' );
	if ( $petition_meta ) 
		$output = array_slice( $petition_meta, $number * -1 );
		return array_reverse( $output );
	
}

Remember when I said it’s going to be kinda-hard? I lied:

  • We assigned the values of the post metas with the ‘petition_submission‘ key to an array variable
  • Then we got $number (5 by default) of submissions from the end of the array (notice the -1)
  • And we returned the reversed list of that sliced array to order it newest to oldest

Extra: CSS Selectors to Use

We’ll be using some CSS selectors in the code, so put them in your style.css file of your theme:

#petition_form {}
#petition_form label 
	font-weight: bold;
	font-size: larger;
	line-height: 150%;

#petition_form input 
	display: block;
	margin: 5px 0;
	padding: 3px;

#petition_name 
	width: 200px;

#petition_email 
	width: 200px;

#petition_submit 
	padding: 5px;

.petition_success 
	color: #693;

.petition_error 
	color: #A00;

.petition_list 
	list-style: none;
	margin: 0;
	padding: 0;

.petition_list li 
	background-image: none !important;

.petition_list span 
	display: inline-block;
	width: 45%;
	padding: 1%;
	margin: 1%;
	background-color: #FAFAFA;

.submission_name {}
.submission_date 
	font-style: italic;
	color: #888;

Feel free to edit the default values of the properties :)

/>

Shortcodes

We completed the helper functions and the CSS code. Now, let’s get to the fun part – the shortcodes!

We could do with just one big shortcode to attach the form, list the entries and show the number of submissions but… why kill all the fun? Besides, separate shortcodes for these three elements would liberate us to use them wherever we want in our content.

Did I tell you how I love shortcodes?

The Shortcode for the Petition Form

This function is a long one, so I’m going to explain the code inside the code, with PHP comments:

function petition_form_sc( $atts ) 
	// extract the shortcode parameters
	extract( shortcode_atts( array(
		// the text value of the submit button
		'submit' => 'Submit',
		// the text for the error message
		'error' => 'Your e-mail address is not valid. Please re-enter the form with a valid name and e-mail address.',
		// the text when the submission is successful
		'success' => 'Your submission has been saved. Thank you!'
	), $atts ) );
	// the HTML elements of our petition form
	$form = '
'; // if the form is "POST"ed... if ( $_SERVER['REQUEST_METHOD'] == 'POST' ) // ...get the name... $name = $_POST['petition_name']; // ...and the e-mail address... $email = $_POST['petition_email']; // ...and the date of "just now", with the date format of your WP options. $date = date( get_option( 'date_format' ) ); // validate the e-mail address first! if ( validate_email( $email ) == true ) // the e-mail address is valid! remember the function below? submission( $name, $email, $date ); // we sent the variables with the submission() function, now we print the success message WITHOUT THE FORM: return '
' . $success . '
'; // (if you want the form to be printed again after the submission, just add .$form before the semicolon.) else // the e-mail address is NOT valid! we should print the error message WITH THE FORM: return '
' . $error . '
' . $form; } // and if the form isn't "POST"ed (meaning the visitor just visited the page), just show the form! else return $form; } add_shortcode( 'petition_form', 'petition_form_sc' );

I tried to be as clear as I can be but if you believe that I left something out, feel free to ask me by commenting on this post!

The Shortcode for the List of Submissions

The “latest entries” part is the proof that people are joining your cause, so we have to list at least some number of submissions.

This is not a short function either, so I’ll explain the code with comments again:

function petition_list_sc( $atts ) 
	// extract the shortcode parameters
	extract( shortcode_atts( array(
		// we could set a default number but remember, we already did that in the get_the_submissions() function :) 
		'number' => ''
	), $atts ) );
	// get the $number latest submissions...
	$submissions = get_the_submissions( $number );
	// ...and list 'em!
	$output = '
    '; if ( $submissions ) foreach( $submissions as $submission ) // unserialize the data $signer = unserialize( $submission ); // unserialize the data AGAIN, don't know why... $signer = unserialize( $signer ); // you might want to change this part, but the default format look great with the CSS in this tutorial. $output .= '
  • '; $output .= '' . $signer['name'] . ''; $output .= '' . $signer['date'] . ''; $output .= '
  • '; } $output .= '
'; return $output; } add_shortcode( 'petition_list', 'petition_list_sc' );

Again, feel free to ask anything you want to ask by commenting on this post.

The Shortcode for the Petition Count

This is a really small function, just to get how many entries are submitted:

function petition_count_sc() 
	$petition_meta = get_post_custom_values( 'petition_submission' );
	return count( $petition_meta );

add_shortcode( 'petition_count', 'petition_count_sc' );

As you can see, it just throws the custom fields to an array and counts it and return the number.

/>

Conclusion

I should emphasize that this is a very simple example to show organizations can benefit from WordPress by utilizing scripts like these. If you can think of an improvement for this script (or tutorial), please share your thoughts in the comments below. Thanks for reading!

Original from: http://wp.tutsplus.com/tutorials/creative-coding/creating-nifty-petitions-inside-your-posts/

Adding a Set of Responsive Grid Shortcodes to Your WordPress Site

August 25th, 2012 Comments off

Today we’ll be taking a basic custom grid created with CSS and integrating it into WordPress via shortcodes. I presume all you readers have a basic understanding of CSS so I won’t be covering any of that here, I’ll also presume that you have a WordPress theme setup already and we’ll just add bits in. Enough said, lets get stuck in!


Step 1: Our CSS Grid

Before we start, we’ll go ahead and create a css folder and then a file inside called grid.css. Because of the amount of mobile and tablet usage now days we’ll go ahead and add the responsive part for our grid too. I’ve gone ahead and commented this to help make it less confusing for anyone not already familiar with it.

/* ---------------------------------------------------------------------- */
/*  Custom Grid
/* ---------------------------------------------------------------------- */

.container 
	margin:0 auto;
	width:940px;
	position:relative;


.container .one-half,
.container .one-third,
.container .one-fourth,
.container .two-thirds,
.container .three-fourths 
	float:left;
	margin-right:20px;


.container .one-half.last,
.container .one-third.last,
.container .one-fourth.last,
.container .two-thirds.last,
.container .three-fourths.last 
	margin-right:0;


.container .one-half        width:460px; 
.container .one-third       width:300px; 
.container .one-fourth      width:220px; 
.container .two-thirds      width:620px; 
.container .three-fourths   width:700px; 

/* ------------------------------------------- */
/*  Responsive Grid - 
/*		1. Tablet
/*		2. Mobile Portrait
/*		3. Mobile Landscape
/* ------------------------------------------- */

@media only screen and (min-width: 768px) and (max-width: 959px) 
	.container                  width:748px; 
	.container .one-half        width:364px; 
	.container .one-third       width:236px; 
	.container .one-fourth      width:172px; 
	.container .two-thirds      width:492px; 
	.container .three-fourths   width:508px; 
}

@media only screen and (max-width: 767px) {
	.container        width:300px; 
	.container .one-half,
	.container .one-third,
	.container .one-fourth,
	.container .two-thirds,
	.container .three-fourths  width:300px; margin-right:0; 
}

@media only screen and (min-width: 480px) and (max-width: 767px) 
	.container        width:420px; 
	.container .one-half,
	.container .one-third,
	.container .one-fourth,
	.container .two-thirds,
	.container .three-fourths  width:420px; margin-right:0; 
}

Step 2: Registering Our CSS Within WordPress

Before we can jump into making any shortcodes we’ll need to register the CSS file we just created. We’ll do this by using wp_register_style and wp_enqueue_style. Be sure to place this within your functions.php or another file which is linked to via the functions.php file. I’ve also gone ahead and wrapped this within a function but this isn’t necessary. Once we’ve called and registered our CSS file we’ll need to hook it using the add_action function.

if ( !function_exists('register_css') ) 

	function register_css() 

		wp_register_style('custom-grid', get_template_directory_uri() . '/css/grid.css');
		wp_enqueue_style('custom-grid');

	

	add_action('wp_enqueue_scripts', 'register_css');
}

Step 3: Starting to Create Our Shortcodes

To keep everything clean we will create a new file called shortcodes.php to keep our shortcodes separate from any other functions, we’ll also need to link to this within our functions.php file.

// Include shortcodes
include 'shortcodes.php';

Step 4: The Shortcode API

The Shortcode API is brilliant, it allows users to create endless things with it. You can pass attributes and values through it. If you’d like to read up more on the Shortcode API, visit the Shortcode API page in the WordPress Codex. To see what shortcodes can do, we will show two paths for this.


Step 6: Shortcode Route 1

Because this is a grid, it will have columns (obviously) but when it gets to the last column we’ll need to define it being the last column because of how the custom grid has been coded. For example, if we had a main area of two-thirds and a sidebar of one-third. The sidebar will need defining as the last one in the row so we will add a class of last to it.

Now we’ll start creating our shortcode, we’ll start off with a basic one-half column shortcode. We start off with creating a function with a name of the shortcode. We’ll then pass two arguments of $atts and $content. The way shortcodes work is very simple, if you’re creating a shortcode like this all we need to do is return something. All we’ll return is a div with the class of one-half along with the content inside it. The last thing to do is to enable the shortcode for use within your WordPress themes. This is done via the add_shortcode function. This function accepts two parameters, the name used to access the shortcode and the function name of the shortcode. We have used ‘one_half‘ for the name to access the shortcode so we can use this within the editor by typing [one_half].

function one_half( $atts, $content = null ) 

	return '
' . do_shortcode( $content ) . '
'; add_shortcode('one_half', 'one_half');

Now, if we look back we spoke about defining the last column. For this route we’ll simply created another shortcode but instead of [one_half], we’ll use [one_half_last] while changing the class name from

to
.

function one_half_last( $atts, $content = null ) 

	return '
' . do_shortcode( $content ) . '
'; add_shortcode('one_half_last', 'one_half_last');

Step 7: Shortcode Route 2

Okay, if you would prefer to not have to create two shortcodes for each column – one for the normal and one for the last column there is an alternative. Instead of creating two we could pass an attribute through our shortcode, for example [one_half last="yes"]. If no attribute is passed, this will not be used as a ‘last‘ column.

A majority of this will look similar, with the exception of some new stuff. We’ll need to extract the shortcode_atts (attributes) first. Next because we defined ‘last‘ as an attribute we’ll need to use an if statement to check whether this is a last column. We’ll do this by checking if $last equals yes, $position equals last. If not, $position equals nothing. Then we can return the same thing but adding the $position variable for the last column option. Now we can access this shortcode still with [one_half] but adding the ‘last‘ attribute and a value of yes – [one_half last="yes"].

function one_half( $atts, $content = null ) 

	extract( shortcode_atts( array(
			'last'   => ''
		), $atts ) );

	if ( $last == 'yes') 
		$position = 'last';
	
	else 
		$position = '';
	

	return '
' . do_shortcode( $content ) . '
'; } add_shortcode('one_half', 'one_half');

Conclusion

Well guys, that was my first tutorial here at Wptuts+, I hope you learnt something today! Feel free to use the CSS grid or shortcodes in your projects! Until next time, let me know your thoughts in the comments!

Original from: http://wp.tutsplus.com/tutorials/creative-coding/adding-a-set-of-responsive-grid-shortcodes-to-your-wordpress-site/

Use Geo Location to Give Your Customers Driving Directions

August 6th, 2012 Comments off

This tutorial is an update to a previous one in which we looked at how to show driving instructions directly on a WordPress Website using the the Google Maps API.

In the first tutorial, our users had to manually enter their address into a form on the website – then the directions would be displayed. This was a good example of how to use the Google Maps API but the ability to detect a users’ current location, in addition to being able to enter an address manually, was a feature often requested.

There’s quite a lot of ground to cover here, but a large portion of it was covered in the previous tutorial. To save me having to repeat myself, please review the first tutorial “Give your Customers Driving Directions” where you’ll find everything that isn’t explained in this one.

What We Covered in the Original

This is a list of things we are not going to cover in this tutorial. So feel free to review the original tutorial for detailed explanations:

  1. How to register custom settings in the WordPress Admin Panel. The three settings fields were for:
    • The destination
    • The text to display in the Info Window
    • The initial Zoom Level of the map when first loaded
  2. How to get a really accurate Lat/Lon value for your destination using the Google Maps API V3 Sample
  3. How to set up the shortcodes used in this tutorial

Note: Reading the first tutorial will help you understand the parts that are not explained in this tutorial. However, the code provided in the source files contains everything you need.


What We’ll Be Creating


Why Is This Better That the Original?

In addition to what we achieved in the previous tutorial, we will also:

  1. Detect whether or not the user’s browser has geo location capabilities
  2. If it does, allow them to use it instead of entering an address manually
  3. Provide a special link to Google Maps. When clicked (or tapped), this link will open up the native Maps application on the device if it’s available and will automatically plan the route. This is especially helpful on iOS and Android devices

Other improvements to the original:

  1. We will look at improved error handling
  2. Previously, the Site Admin had to enter the Latitude & Longitude values of the destination in the WordPress Settings – today we’ll look at how to accept these Lat/Lon values or a regular address. This means the Admin can either provide a pin-pointed spot on the map (exact position of a building, for example) or just simply the street address instead.

Step 1 Create a CSS File

We’ll be adding a tiny bit of CSS to improve the look/layout of our map and buttons, so we’ll create an external CSS stylesheet in our map directory.

Inside your theme folder, your map directory should now look like this:

  • map.php
  • map.js
  • map.css

Step 2 Add Some CSS

In the first tutorial, we added a couple of lines of CSS into the theme’s main stylesheet, style.css. Grab those lines and insert them into this new CSS file along with everything you see below.

Note: These styles were written to work with the stock Twenty Eleven theme. You may find that the padding, margins or colours may not suit your theme perfectly. Therefore you should feel free to adjust any of this – it won’t affect the functionality :)

	#map-container img  max-width: none;           /* From original tut */
	#map-container  width: 100%; height: 400px;    /* From original tut */

	/* reduce the height of the map on smaller screens */
	@media only screen and (max-width: 767px) 
		#map-container  height: 235px; 
	}

	/* A class we'll use to hide some elements later */
	.hidden  display: none; 

	/* Button styles - edit at will! */
	.map-button 
		display: block;
		padding: 5px;
		background: #d9edf7;
		border: 1px solid #bce8f1;
		color: #3a87ad;
		margin: 5px 0;
		border-radius: 3px;
		text-shadow: 1px 1px 1px white;
	

	.map-button:hover, .map-button:focus 
		background: #b1dce5;
		text-decoration: none;
	

	/* Cancel out any default padding on 'p' elements */
	#directions p 
		margin-bottom: 0;
	

	/* Adjust how the input element displays */
	#from-input 
		margin: 5px 0;
		border-radius: 3px;
		padding: 5px;
	

Now you can go ahead and enqueue the file inside the wpmap_map shortcode.

	wp_register_style('wptuts-style', get_template_directory_uri() . '/map/map.css', '', '', false);
	wp_enqueue_style ('wptuts-style');

Step 3 Add the New HTML for the Buttons

Now let’s add the markup for the buttons into our wpmap_directions_input shortcode.

  1. Because we only want our new ‘geo’ buttons to appear for users that have the capability, we’ll wrap our buttons in a div and apply the ‘hidden‘ class that we defined in our CSS. Then we can remove this class later if geo location is enabled.
  2. This time we’re sending a parameter to the WPmap.getDirections method (‘manual‘ or ‘geo‘) – this allows us to have the original functionality (where a user enters an address manually) along with the new geo location method.
  3. The empty span tag is where we’ll insert the special link that will open up the Map application on mobiles and tablets. There’s a bit of work involved with constructing the link correctly, so we’ll take a closer look at that later in the JavaScript section of this tutorial.
	function wpmap_directions_input() 

		$address_to = get_option('map_config_address');

		$output = '

For Driving Directions, Enter your Address below :

Get Driving Directions
'; return $output;

Quick Recap

So far, in relation to the original tutorial, we have:

  1. Created a CSS file with some basic styling and enqueued it.
  2. Added extra markup to allow for new buttons that will only be seen by modern browsers.

Next, we’ll take a look at the JavaScript modifications. There’s quite a lot to this next section, so instead of doing a direct comparison with the original, I’ll just do my best to explain what is happening in each method/function and you can review the full source files at the end to see how it all fits together.


Step 4 The JavaScript

Now here comes the fun part. In the first tutorial, our init() method was responsible for instantiating the map in the same format for every page load. This meant that everyone would receive the exact same functionality regardless of device capabilities – it’s time to change that!

When a user visits our website using a smartphone, for example, we want to be able to offer them the ability to use their current location instead of manually entering it. Also, we want the ability to launch the native Maps application on the phone and have the route automatically planned.

A Quick Word About Browser Support

The GeoLocation JavaScript API is one of the most well supported of all the so-called HTML5 new features. Over 75% of all browsers seem to support it according to caniuse.com. I think that means we’re pretty safe! (We’ll be providing a fall-back for older browsers anyway :) )

Now, let’s dig into the JavaScript.

Understanding the Code

Put simply, all we are looking to do here is provide the option to use geo location if it’s available. If it isn’t, users will still be able to enter an address manually.

If you take a look at the simplified control flow (below), you can see that we use the same methods to set-up the map, but a couple more if geo location is enabled.

OK, I think we have a good understanding of what we’re trying to accomplish here so now I’ll provide an explanation of each method individually – as always, please refer to the source files to see how everything fits together in the same file.

Set Properties

Here we query the DOM to retrieve some properties that we’ll use later. We also get a couple of objects from the API that will handle the ‘get directions’ request.

	var WPmap = 

		// HTML Elements we'll use later!
		mapContainer   : document.getElementById('map-container'),
		dirContainer   : document.getElementById('dir-container'),
		toInput        : document.getElementById('map-config-address'),
		fromInput      : document.getElementById('from-input'),
		unitInput      : document.getElementById('unit-input'),
		geoDirections  : document.getElementById('geo-directions'),
		nativeLinkElem : document.getElementById('native-link'),
		startLatLng    : null,
		destination    : null,
		geoLocation    : null,
		geoLat         : null,
		geoLon         : null,

		// Google Maps API Objects
		dirService     : new google.maps.DirectionsService(),
		dirRenderer    : new google.maps.DirectionsRenderer(),
		map            : null,

		/** WPmap Object continues throughout tutorial **/

init()

This is the first method that will be called when our page is loaded.

  1. The first thing we do is check for geo location capabilities in the browser.
    • If it’s available – we run through a few more methods to set-up the additional buttons on the page (we’ll look at those shortly)
    • If it isn’t available, we skip all of that and move straight on to setting up the destination
  2. The last part of the init() method is the event handler that we use to display a message to the user when directions are requested. Note: This is optional – feel free to remove it.
	init:function () 

		if (WPmap.geoLoc = WPmap.getGeo()) 
			// things to do if the browser supports GeoLocation.
			WPmap.getGeoCoords();
		

		WPmap.getDestination();

		// listen for when Directions are requested
		google.maps.event.addListener(WPmap.dirRenderer, 'directions_changed', function () 

			infoWindow.close();         //close the first infoWindow
			marker.setVisible(false);   //remove the first marker

			// setup strings to be used.
			var distanceString = WPmap.dirRenderer.directions.routes[0].legs[0].distance.text;

			// set the content of the infoWindow before we open it again.
			infoWindow.setContent('Thanks!
It looks like you're about ' + distanceString + ' away from us.
Directions are just below the map'); // re-open the infoWindow infoWindow.open(WPmap.map, marker); setTimeout(function () infoWindow.close() , 8000); //close it after 8 seconds. }); }//init

Ok, I have shown the init() method first this time so that you can understand how the control flow will work.

Now I’ll show you the methods involved when a user has geo location capabilities.


Detecting Geo Location

getGeo()

It all starts with standard ‘feature detection’.

To determine whether a browser supports GeoLocation or not, all we do is check for the existence of the navigator.geolocation object.

	getGeo : function() 
		if (!! navigator.geolocation)
			return navigator.geolocation;
		else
			return undefined;
	,

getGeoCoords()

Now that we know the browser has geo location, we can go ahead and request the current co-ordinates.

  1. We call getCurrentPosition() and pass two parameters – a success callback function and an error callback function
	getGeoCoords : function () 
		WPmap.geoLoc.getCurrentPosition(WPmap.setGeoCoords, WPmap.geoError)
	,

setGeoCoords()

This is our success callback. If we get this far, we have successfully retrieved the coordinates of the user.

  1. position will be an object containing the geo location information so we can go ahead and set the Lat/Lon values to object properties.
  2. Next we call showGeoButton() to show the button for using current location.
  3. Finally we call setNativeMapLink() to construct the link that will open up native map applications.
	setGeoCoords : function (position) 
		WPmap.geoLat = position.coords.latitude;
		WPmap.geoLon = position.coords.longitude;
		WPmap.showGeoButton();
		WPmap.setNativeMapLink();
	,

geoError()

This will handle any errors received from getCurrentPosition() – this is very helpful in development, but in production you may want to remove it as we are providing a fallback to the manual address entry anyway.

	geoError : function(error) 
		var message = "";
		// Check for known errors
		switch (error.code) 
			case error.PERMISSION_DENIED:
				message = "This website does not have permission to use the Geo location API";
				break;
			case error.POSITION_UNAVAILABLE:
				message = "Sorry, your current position cannot be determined, please enter your address instead.";
				break;
			case error.PERMISSION_DENIED_TIMEOUT:
				message = "Sorry, we're having trouble trying to determine your current location, please enter your address instead.";
				break;
		
		if (message == "") 
			var strErrorCode = error.code.toString();
			message = "The position could not be determined due to an unknown error (Code: " + strErrorCode + ").";
		
		console.log(message);
	},

showGeoButton

Show the ‘get current location’ button.

  1. Our approach is to always hide the button, unless both JavaScript and Geo Location are enabled. We accomplish this by removing the .hidden class using .removeClass(). This is a helper method that makes removing classes on HTML elements much simpler (it’ll be at the bottom of the source files)
	showGeoButton : function() 
		var geoContainer = document.getElementById('geo-directions');
		geoContainer.removeClass('hidden');
	,

setNativeMapLink()

This is the special link that will open up native map applications on iOS and Android devices. Because we previously saved the current Lat/Lon values to our object, we can now easily generate the link with the correct format.

	setNativeMapLink: function() 
		var locString   = WPmap.geoLat + ',' + WPmap.geoLon;
		var destination = WPmap.toInput.value;
		var newdest     = destination.replace(' ', '');
		WPmap.nativeLinkElem.innerHTML = ('Open in Google Maps');
	,

getDestination()

Here we are determining whether the Admin has entered a Lat/Lon value or a regular address in the Options page:

  1. We first test to see if toInput is a Lat/Lon value by using a regular expression.
  2. If it is, then we set WPmap.destination equal to a google.maps.LatLng object.
  3. If it isn’t, then we use google.maps.Geocoder() to convert the address into a google.maps.LatLng object and set that as the destination.
  4. Either way, now everything is in place to setup the map using setupMap()
	getDestination:function() 

		var toInput = WPmap.toInput.value;
		var isLatLon  = (/^(-?d+(.d+)?),s*(-?d+(.d+)?)$/.test(toInput));

		if (isLatLon) 
			var n = WPmap.toInput.value.split(",");
			WPmap.destination = new google.maps.LatLng(n[0], n[1]);
			WPmap.setupMap();
		
		else 
			geocoder = new google.maps.Geocoder();
			geocoder.geocode(  'address': WPmap.toInput.value, function(results, status) 
				WPmap.destination = results[0].geometry.location;
				WPmap.setupMap();
			);
		}

	},

setupMap()

Very similar to the original – setup the map with the marker centered on our destination and the text from the Admin options inside the infoWindow.

	/* Initialize the map */
	setupMap : function() 

		// get the content
		var infoWindowContent = WPmap.mapContainer.getAttribute('data-map-infowindow');
		var initialZoom       = WPmap.mapContainer.getAttribute('data-map-zoom');

		WPmap.map = new google.maps.Map(WPmap.mapContainer, 
			zoom:parseInt(initialZoom), // ensure it comes through as an Integer
			center:WPmap.destination,
			mapTypeId:google.maps.MapTypeId.ROADMAP
		);

		marker = new google.maps.Marker(
			map:WPmap.map,
			position:WPmap.destination,
			draggable:false
		);

		// set the infowindow content
		infoWindow = new google.maps.InfoWindow(
			content:infoWindowContent
		);
		infoWindow.open(WPmap.map, marker);

	},

getDirections()

This is called whenever directions are requested. Its only argument, ‘request‘, will help us determine whether the user clicked the button to use a manually entered address or the ‘current location’ one.

	getDirections:function (request) 

		// Get the postcode that was entered
		var fromStr = WPmap.fromInput.value;

		var dirRequest = 
			origin      : fromStr,
			destination : WPmap.destination,
			travelMode  : google.maps.DirectionsTravelMode.DRIVING,
			unitSystem  : WPmap.getSelectedUnitSystem()
		;

		// check if user clicked 'use current location'
		if (request == 'geo') 
			var geoLatLng = new google.maps.LatLng( WPmap.geoLat , WPmap.geoLon );
			dirRequest.origin = geoLatLng;
		

		WPmap.dirService.route(dirRequest, WPmap.showDirections);
	},

showDirections()

Unchanged from the original – it handles the insertion of the directions into the page.

	/**
	 * Output the Directions into the page.
	 */
	showDirections:function (dirResult, dirStatus) 
		if (dirStatus != google.maps.DirectionsStatus.OK) 
			switch (dirStatus) 
				case "ZERO_RESULTS" :
					alert ('Sorry, we can't provide directions to that address (you maybe too far away, are you in the same country as us?) Please try again.');
					break;
				case "NOT_FOUND" :
					alert('Sorry we didn't understand the address you entered - Please try again.');
					break;
				default :
					alert('Sorry, there was a problem generating the directions. Please try again.')
			
			return;
		}
		// Show directions
		WPmap.dirRenderer.setMap(WPmap.map);
		WPmap.dirRenderer.setPanel(WPmap.dirContainer);
		WPmap.dirRenderer.setDirections(dirResult);
	},

Finishing off the JavaScript

Outside of the object, there’s just the event listener to add that will load the map when the page is ready and the helper function we talked about earlier.

	/* Load the map when the page is ready */
	google.maps.event.addDomListener(window, 'load', WPmap.init);

	/* Function to easily remove any class from an element. */
	HTMLElement.prototype.removeClass = function(remove) 
		var newClassName = "";
		var i;
		var classes = this.className.split(" ");
		for(i = 0; i < classes.length; i++) 
			if(classes[i] !== remove) 
				newClassName += classes[i] + " ";
			
		}
		this.className = newClassName;
	}

And Finally…

Now to get everything working you just need to put the map folder into your theme and then run through the things we covered in the first tutorial.

  1. Include map.php in your theme’s functions.php

    			/** In functions.php **/
    			include('map/map.php');
    		
  2. Enter your destination, infowindow text and zoom level into the fields that we created in Settings. They can be found under Settings -> General -> Map Configuration
  3. Then, on any page or post, enter the three shortcodes
    1. [wpmap_map]
    2. [wpmap_directions_input]
    3. [wpmap_directions_container]

Conclusion

As I’ve mentioned this is an update to this tutorial and therefore you really need to review both of them to fully understand the entire process. Possibly the easiest way to understand how it all fits together would be to view the source files provided though.

After all of this you should have a pretty neat little map application that will respond to different screen sizes and also add extra functionality to users with modern browsers. All the while providing a good fallback for everyone else.

Original from: http://wp.tutsplus.com/tutorials/creative-coding/use-geo-location-to-give-your-customers-driving-directions/

Create an FAQ Accordion for WordPress With jQuery UI

June 17th, 2012 Comments off

Creating an FAQ section for your WordPress website is incredibly simple. We’re going to use WordPress Custom Post Types for the questions & answers. Then we’ll use a jQuery UI accordion to make a nice cross-browser accordion widget. Finally we’ll assign a shortcode so that we can put our FAQ on any page or post.

We’ll be creating this:


Step 1 Create the Directory and Files

  1. Create a new folder inside your theme folder called faq
  2. Inside the ‘faq‘ folder, create a new file called faq.php
  3. Create another file called faq.js

Step 2 Include the faq.php File

In your functions.php (located in the root directory of your theme) – include the faq.php file you created at the top.

/* functions.php */
include('faq/faq.php');

Step 3 Create the Custom Post Type

  1. To register the Custom Post Type, we are going to hook into the init action. We are using an anonymous function as the second parameter to help keep everything encapsulated in one place. This helps with readability and maintainability.
  2. Set up $labels and $args as seen below.
  3. At the end we call register_post_type('FAQ', $args)
  4. Now if you go into your Admin area you will see a new option in the menu – FAQ (as seen in the image below)
  5. Click Add New Question and enter a few Questions and Answers so that we have something to work with later on. Use the title field for the question, and the main content field for the answer. This allows us to enter any type of content into our answer (such as images & videos) as well as text.
/* Register the Custom Post Type */
/* faq.php */
add_action('init', function() 

	$labels = array(
		'name' => _x('FAQ', 'post type general name'),
		'singular_name' => _x('Question', 'post type singular name'),
		'add_new' => _x('Add New Question', 'Question'),
		'add_new_item' => __('Add New Question'),
		'edit_item' => __('Edit Question'),
		'new_item' => __('New Question'),
		'all_items' => __('All FAQ Questions'),
		'view_item' => __('View Question'),
		'search_items' => __('Search FAQ'),
		'not_found' => __('No FAQ found'),
		'not_found_in_trash' => __('No FAQ found in Trash'),
		'parent_item_colon' => '',
		'menu_name' => 'FAQ'
	);

	$args = array(
		'labels' => $labels,
		'public' => true,
		'publicly_queryable' => true,
		'show_ui' => true,
		'show_in_menu' => true,
		'query_var' => true,
		'rewrite' => true,
		'capability_type' => 'post',
		'has_archive' => true,
		'hierarchical' => false,
		'menu_position' => null,
		'supports' => array('title', 'editor', 'page-attributes')
	);
	register_post_type('FAQ', $args);
);

Step 4 Include jQuery, jQuery UI, and faq.js

  1. Load jQuery
  2. Load jQuery UI
  3. Load the stylesheet for the jQuery UI library
  4. Load our custom script faq.js
add_action( 'wp_enqueue_scripts', 'wptuts_enqueue' );
function wptuts_enqueue() 
	wp_register_style('wptuts-jquery-ui-style', 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.21/themes/south-street/jquery-ui.css');
	wp_enqueue_style('wptuts-jquery-ui-style');

	wp_register_script('wptuts-custom-js', get_template_directory_uri() . '/faq/faq.js', 'jquery-ui-accordion', '', true);
	wp_enqueue_script('wptuts-custom-js');

You’ll notice we only used one wp_enqueue_script call, because it’s important the JavaScript files are loaded in order as they are dependent on each other. Setting jquery-ui-accordion as a dependency makes sure this happens.


Step 5 Setup the Shortcode

Because we want to be able to put our FAQ Accordion on any page/post, we’re going to generate a shortcode. Using a shortcode means that we only have to type [faq] inside any post/page in the WordPress Editor to display our FAQ.

add_shortcode('faq', function() 
	return "Shortcode test";
);

Step 6 Get the FAQ Questions & Answers

We can get the data from our custom post type by using the get_posts() function.

  1. numberposts – Here you can limit how many FAQ questions are retrieved
  2. orderby and order – Allows us to change the order of the questions
  3. post_type – This is how we tell WordPress to only fetch our custom post type
add_shortcode('faq', function() 
	$posts = get_posts( array(
		'numberposts' => 10,
		'orderby' => 'menu_order',
		'order' => 'ASC',
		'post_type' => 'faq'
	)); //array of objects returned
);
/* example */
echo $posts[0]->post_content; // will output the answer from the first faq question.

Step 7 Generate the Markup for the jQuery UI Accordion

This is the markup needed for the jQuery UI Accordion :


Question Will Go Here

Answer will be in this div.

We can generate this by looping over the $posts array.

  1. First we use $faq to store the start of our HTML – we open up a div with an id of wptuts-accordion
  2. Next we start looping through all the posts and adding the result of sprintf to the $faq variable.
  3. sprintf will replace %1$s with the value retrieved from $post->post_title and %2$s with the value returned from $post->post_content
  4. We run $post->post_content through wpautop() to ensure it displays as it was authored in the admin area.
  5. Finally we close off the div and return $faq to output the HTML onto our page.
	$faq  = '
'; // the container, before the loop foreach ( $posts as $post ) $faq .= sprintf(('

%1$s

%2$s
'), $post->post_title, wpautop($post->post_content) ); $faq .= '
'; // finish off by closing the container return $faq;

The Full Shortcode

add_shortcode('faq', function() 

	$posts = get_posts(array(  //Get the FAQ Custom Post Type
		'numberposts' => 10,
		'orderby' => 'menu_order',
		'order' => 'ASC',
		'post_type' => 'faq',
	));

	$faq  = '
'; //Open the container foreach ( $posts as $post ) // Generate the markup for each Question $faq .= sprintf(('

%1$s

%2$s
'), $post->post_title, wpautop($post->post_content) ); $faq .= '
'; //Close the container return $faq; //Return the HTML. });

Final Step

Phew! If you have got this far, well done – you’re nearly there! At the moment we’ve managed to output all the data needed for our accordion, all that’s left to do is place this in faq.js:

(function()
	jQuery("#wptuts-accordion").accordion();
)();

Original from: http://wp.tutsplus.com/tutorials/creative-coding/create-an-faq-accordion-for-wordpress-with-jquery-ui/

Using the Envato API with WordPress

February 8th, 2012 Comments off

Today we are going to discuss how to use the Envato API in WordPress and create a WordPress shortcode that promotes our Envato Marketplace Items inside our WordPress site. We will combine the powerful Envato API, WordPress’ flexibility and a little bit of creativity, to build an amazing plugin for our site.


Let’s Set Our Goal

In this tutorial we are going to focus on:

  • Some basic knowledge about the Envato API
  • How to use API result data inside WordPress
  • Build a WordPress Shortcode that promotes Envato Marketplace items in our WordPress site.

So let’s get into the first one!


Step 1: Understanding the Envato API

Envato provides an API that allows developers to get some information about Envato Marketplace items, users info, popular projects and so on. All possible queries are listed in the official documentation. In this article we discuss the public API only.

The Envato Public API has the following structure.


http://marketplace.envato.com/api/edge/set.json

The word set must to be replaced with an option listed in the set column of the API documentation. So if we want all information about a marketplace item we have to replace set with item:the_item_id. The final request URL will be:


http://marketplace.envato.com/api/edge/item:1263846.json

You can try to insert the URL above in your web browser and see the returned data.

We can also concatenate more than one set option in a single request to get more data. For example we want the item data and its author information. So the previous URL will become:


http://marketplace.envato.com/api/edge/item:1263846+user:evoG.json

The Envato API returns JSON, so in the next paragraph we are going to show how to manage it in WordPress.


Step 2: How to Use API Results in WordPress

In this tutorial we are not going to discuss how to create a WordPress plugin, but we are going to focus on some techniques to use the API in WordPress:

  • Send the API request
  • Manage the result data (the JSON string)

The function below fetches the data from the Envato server and returns a PHP array that contains all the informations we want.

/**
 * @param String $item_id - The ID of an Envato Marketplace item
 * @returns Array - The item informations
 */
function WPTP_get_item_info( $item_id ) 

	/* Set the API URL, %s will be replaced with the item ID  */
	$api_url = "http://marketplace.envato.com/api/edge/item:%s.json";

	/* Fetch data using the WordPress function wp_remote_get() */
	$response = wp_remote_get( sprintf( $api_url, $item_id ) );

	/* Check for errors, if there are some errors return false */
	if ( is_wp_error( $response ) or ( wp_remote_retrieve_response_code( $response ) != 200 ) ) 
		return false;
	

	/* Transform the JSON string into a PHP array */
	$item_data = json_decode( wp_remote_retrieve_body( $response ), true );

	/* Check for incorrect data */
	if ( !is_array( $item_data ) ) 
		return false;
	

	/* Return item info array */
	return $item_data;

}

We can improve the function above. To prevent stress on the Envato API server we can cache item data and request the info again after a timeout. WordPress offers us some functions to implement this feature. Let’s add it.

/**
 * @param String $item_id - The ID of an Envato Marketplace item
 * @returns Array - The item informations
 */
function WPTP_get_item_info( $item_id ) 

	/* Data cache timeout in seconds - It send a new request each hour instead of each page refresh */
	$CACHE_EXPIRATION = 3600;

	/* Set the transient ID for caching */
	$transient_id = 'WPTP_envato_item_data';

	/* Get the cached data */
	$cached_item = get_transient( $transient_id );

	/* Check if the function has to send a new API request */
	if ( !$cached_item 

		/* Transform the JSON string into a PHP array */
		$item_data = json_decode( wp_remote_retrieve_body( $response ), true );

		/* Check for incorrect data */
		if ( !is_array( $item_data ) ) 
			return false;
		

		/* Prepare data for caching */
		$data_to_cache = new stdClass();
		$data_to_cache->item_id = $item_id;
		$data_to_cache->item_info = $item_data;

		/* Set the transient - cache item data*/
		set_transient( $transient_id, $data_to_cache, $CACHE_EXPIRATION );

		/* Return item info array */
		return $item_data;

	}

	/* If the item is already cached return the cached info */
	return $cached_item->item_info;

}

Now the core function of our WordPress plugin is ready. We have used some WordPress functions that help us to save time. All information about them is explained in the official WordPress Codex.


Step 3: Build WordPress Shortcode

In the next steps we are going to code a useful WordPress plugin that allows us to display some informations about an Envato Marketplace item. All code below is well commented so you can easily understand each line. For more details about Writing a WordPress Plugin and the WordPress Shortcode API check out the online documentation in the WordPress Codex.

Let’s start

Let’s write the header informations for our plugin


Add the WordPress shortcode

Now we write the code to add the shortcode and its functionalities.

 ''
	), $atts );

	extract( $atts );

	/* Validation */
	if ( empty( $item_id ) ) 
		return "

Please insert an Envato Marketplace Item ID.

"; /* Get data from the API*/ $item = WPTP_get_item_info( $item_id ); /* Validation - Check if something went wrong */ if ( $item === false ) return "

Oops… Something went wrong. Please check out the item ID and try again.

"; /* Format the $item array */ $item = $item['item']; extract( $item ); /* Prepare the Plugin HTML */ $html = ''; $html .= '
'.$item.'
rating'. WPTP_get_stars($rating) .'
'.$sales.' sales
'.$item.'
$'.round($cost).' only
'; return $html; }

Star ratings function

The WPTP_add_shortcode() function above has the WPTP_get_stars() procedure that coverts the rating number to HTML stars. Let’s implement it.

Not rate yet
'; /* Else if rating is >= 1 the function converts it to HTML stars and returns them as a string */ $return = '
    '; $i=1; while ( ( --$rating ) >= 0 ) $return .= '
  • '; $i++; if ( $rating == -0.5 ) $return .= '
  • '; $i++; while ( $i <= 5 ) $return .= '
  • '; $i++; $return .= '
'; return $return; }

Include CSS

When the shortcode functions are completed, we have to include the style.css file that styles our plugin.



Step 4: Write CSS Rules

The style.css file is inside the same directory as the main plugin file and it contains all the CSS rules.

/* WordPress Tutsplus Envato Item Info - CSS Rules*/

/* Main layout and typography */
.wptp_envato_item 
	font-family: "Helvetiva Neue", Arial, sans-serif;
	margin: 20px 0;


.wptp_wrap  width: 210px; 

.wptp_text  display: block; 

.wptp_num 
	display: block;
	font-size: 24px;
	font-weight: 300;
	margin: 0;
	padding: 0;
	line-height: 24px;
	color: #66696d;


.wptp_num span 
	font-size: 14px;
	vertical-align: super;


.wptp_desc 
	display: block;
	font-size: 12px;
	font-weight: 300;
	margin: 0;
	padding: 0;
	line-height: 12px;
	color: #96999d;


.wptp_not_rating 
	color: #66696d;
	font-size: 13px;
	font-weight: bold;


.wptp_title  font-size: 14px; font-weight: 300; color: #66696d; margin-bottom: 10px; 

/* Stars rating section */

.wptp_rating 
	width: 82px;
	text-align: center;
	margin: 0 auto 10px auto;


.wptp_stars 
	margin: 0;
	padding: 0;
	list-style: none;


.wptp_stars li 
	margin-left: 2px;
	display: inline-block;
	vertical-align: middle;
	width: 13px;
	height: 13px;


.wptp_stars li.wptp_full_star  background: url(icons-sprite.png) 0px -64px ; 

.wptp_stars li.wptp_empty_star  background: url(icons-sprite.png) -14px -64px ; 

/* Sales and Price sections */
.wptp_sales, .wptp_thumb, .wptp_price 
	display: inline-block;
	vertical-align: middle;


.wptp_sales 
	text-align: right;
	margin-right: 10px;


.wptp_sales .wptp_text 
	width: 52px;


.wptp_img_sales 
	background: url(icons-sprite.png) 0px 0px;
	width: 32px;
	height: 32px;
	display: block;
	margin: 0 0 12px 20px;


.wptp_img_price 
	background: url(icons-sprite.png) 0px -32px ;
	width: 32px;
	height: 32px;
	display: block;
	margin-bottom: 7px;


.wptp_price 
	text-align: left;
	margin-left: 10px;


.wptp_price .wptp_text  width: 34px; 

/* Purchase button section */
.wptp_bottom a 
	display: block;
	width: 78px;
	height: 33px;
	background: url(icons-sprite.png) -32px 0px;
	margin: 10px auto 0 auto;


Conclusion

That’s it, now we can upload the plugin to our Worpdress site and use the power of WordPress shortcodes to display some info about Envato Marketplace items. For more details about Writing a WordPress Plugin and the WordPress Shortcode API check out the online documentation on the WordPress Codex.

I’m Michele Ivani and I hope this tutorial was helpful for your WordPress development. Thanks so much for reading.

Original from: http://wp.tutsplus.com/tutorials/using-the-envato-api-with-wordpress/