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/
Categories: Wordpress Tags: 2012-at-427-pm, author, code, creative coding, facebook, find-out-more, grid, responsive, shortcodes, tutorial, twitter, twitter-google
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:
- 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
- How to get a really accurate Lat/Lon value for your destination using the Google Maps API V3 Sample
- 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:
- Detect whether or not the user’s browser has geo location capabilities
- If it does, allow them to use it instead of entering an address manually
- 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:
- We will look at improved error handling
- 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:
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.
- 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.
- 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.
- 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 = '';
return $output;
Quick Recap
So far, in relation to the original tutorial, we have:
- Created a CSS file with some basic styling and enqueued it.
- 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.
- 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
- 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.
- 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.
position will be an object containing the geo location information so we can go ahead and set the Lat/Lon values to object properties.
- Next we call
showGeoButton() to show the button for using current location.
- 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.
- 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:
- We first test to see if
toInput is a Lat/Lon value by using a regular expression.
- If it is, then we set
WPmap.destination equal to a google.maps.LatLng object.
- 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.
- 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.
-
Include map.php in your theme’s functions.php
/** In functions.php **/
include('map/map.php');
- 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
- Then, on any page or post, enter the three shortcodes
[wpmap_map]
[wpmap_directions_input]
[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/
Categories: Wordpress Tags: author, code, conclusion, creative coding, directions, facebook, geo location, google-maps, shane-osbourne, shortcodes, twitter
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
- Create a new folder inside your theme folder called faq
- Inside the ‘faq‘ folder, create a new file called faq.php
- 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
- 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.
- Set up
$labels and $args as seen below.
- At the end we call
register_post_type('FAQ', $args)
- Now if you go into your Admin area you will see a new option in the menu – FAQ (as seen in the image below)
- 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
- Load jQuery
- Load jQuery UI
- Load the stylesheet for the jQuery UI library
- 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.
numberposts – Here you can limit how many FAQ questions are retrieved
orderby and order – Allows us to change the order of the questions
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 :
Answer will be in this div.
We can generate this by looping over the $posts array.
- First we use
$faq to store the start of our HTML – we open up a div with an id of wptuts-accordion
- Next we start looping through all the posts and adding the result of
sprintf to the $faq variable.
sprintf will replace %1$s with the value retrieved from $post->post_title and %2$s with the value returned from $post->post_content
- We run
$post->post_content through wpautop() to ensure it displays as it was authored in the admin area.
- 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(('
%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(('
%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/
Categories: Web development, Wordpress Tags: adobe, article, audio, development, facebook, hosting, javascript, jquery, photography, security, shortcodes, videos
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)
.'
';
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/
Recent Comments