Archive

Posts Tagged ‘css’

Add Lazy Loading Social Sharing Buttons to your WordPress Blog

September 2nd, 2012 Comments off

One of the most common and important parts of every blog is a collection of social media buttons i.e. Facebook’s Like button, Twitter’s tweet button, Google’s +1 button etc. Each social platform adds a JavaScript file with its buttons, this means when a blog page loads it has to wait for the 300kb of social media. This hangs the rendering of the page which results in increased page load time. To resolve this issue some of the really big blogs have devised certain techniques through which the social media buttons can be loaded asynchronously. In this tutorial you will learn how to add this “lazy loading” social sharing buttons to your WordPress blog.


Introduction:

These icons will be using a JavaScript library made by . .Net magazine published the Big question: should we drop social media buttons? with opinions and anecdotes from various professionals. This inspired him to reply to them with a nice handy code snippet.

Social widgets are massive. They’re effectively additional websites sand-boxed within tiny iframes and most are poorly optimized. Facebook’s “like” button is appalling. This problem cannot be understated and I developed Socialite.js for exactly that reason. Socialite defers loading and works extremely well. It doesn’t reduce the amount of bytes being shipped, but it does let your website load first before the stream is saturated with social extras.
- David


Some Words About Socialite

Socialite provides a very easy way to implement and activate a plethora of social sharing buttons — any time you wish. On document load, on article hover, on any event!

If you’re selling your soul, you may as well do it asynchronously.
- David

Features and Benefits

  • No dependencies to use.
  • Loads external resources only when needed.
  • Less than 5kb when minified and compressed.
  • More accessible and styleable defaults/fallbacks.
  • Support for Twitter, Google+, Facebook, LinkedIn, Pinterest, and Spotify.
  • Extensible with other social networks.
  • Mimics native implementation when activated.
  • Supported in all browsers (providing the buttons are).

Step 1 Uploading the JavaScript

Let’s roll. First step is to upload the socialite.min.js file, which I recommend you load in your footer. Download the package from socialitejs.com, open it, and upload the socialite.min.js file to your wp-content/themes/your-theme-folder/js/ folder (if the js folder doesn’t exist, create it first).


Step 2 Adding the Script to the Footer

Add Socialite

After uploading the JS file to your theme’s folder, add the following code into your theme’s functions.php file.

function wptuts_load_socialite() 

	// Register Socialite
	wp_register_script( 'socialite', get_template_directory_uri() . '/js/socialite.min.js', array(), '', true );

	// Now enqueue Socialite
	wp_enqueue_script( 'socialite' );

add_action( 'wp_enqueue_scripts', 'wptuts_load_socialite' );

Initialize Socialite

Now create a new JS file in your wp-content/themes/your-theme-folder/js/ folder called wptuts-social.js and put the following code in it.

jQuery(document).ready(function($) 
	$('.social-buttons').one('mouseenter', function() 
		Socialite.load($(this)[0]);
	);
});

Now we have a second JS file, we need to amend the PHP code we added to our functions.php file, so it should now look like the following.

function wptuts_load_socialite() 

	// Register Socialite
	wp_register_script( 'socialite', get_template_directory_uri() . '/js/socialite.min.js', array(), '', true );
	// Register social initialiser script
	wp_register_script( 'wptuts-social', get_template_directory_uri() . '/js/wptuts-social.js', array('jquery', 'socialite'), '', true );

	// Now enqueue Socialite
	wp_enqueue_script( 'wptuts-social' );

add_action( 'wp_enqueue_scripts', 'wptuts_load_socialite' );

What Is This Code?

In the first step you uploaded socialite.min.js to your theme’s folder, after that in the second step you included that script in your theme’s footer. Then you added a little code to trigger the social button on the mouseenter property for a specific class i.e. the class of our social buttons is social-buttons, when the mouse enters into that class or you could say when someone hovers the mouse over the social-buttons class, the social sharing buttons will load right at that moment.

In the code above this line is responsible for triggering the social buttons, you can change its class (i.e. social-buttons) to any other you want.

	$('.social-buttons').one('mouseenter', function() 

Step 3 Adding the CSS

We will discuss where to add the HTML later, let’s add the CSS first. So, we are about to add the CSS which will hide the button’s text and will show an image in place of them when they are not loaded. You are free to modify the CSS to suit your theme, that way it will make you stand out from others. David has coded the following CSS.

Create a new CSS file called wptuts-social.css in your wp-content/themes/your-theme-folder/css/ folder (if the css folder doesn’t exist, create it first).

Then add the following code into the file.

/*
 * Socialite Look-a-like defaults
 */

.social-buttons  display: block; list-style: none; padding: 0; margin: 20px; 
.social-buttons > li  display: block; margin: 0; padding: 10px; float: left; 
.social-buttons .socialite  display: block; position: relative; background: url('http://tuts-authors.s3.amazonaws.com/wp.tutsplus.com/AhmadAwais/2012/08/29/social-sprite.png') 0 0 no-repeat; 
.social-buttons .socialite-loaded  background: none !important; 

.social-buttons .twitter-share  width: 55px; height: 65px; background-position: 0 0; 
.social-buttons .googleplus-one  width: 50px; height: 65px; background-position: -75px 0; 
.social-buttons .facebook-like  width: 50px; height: 65px; background-position: -145px 0; 
.social-buttons .linkedin-share  width: 60px; height: 65px; background-position: -215px 0; 

.vhidden  border: 0; clip: rect(0 0 0 0); height: 1px; margin: -1px; overflow: hidden; padding: 0; position: absolute; width: 1px; 

Now let’s go back and modify the PHP code we put into our functions.php file again to load the new CSS file, as follows.

function wptuts_load_socialite() 

	// Register Socialite
	wp_register_script( 'socialite', get_template_directory_uri() . '/js/socialite.min.js', array(), '', true );
	// Register social initialiser script
	wp_register_script( 'wptuts-social', get_template_directory_uri() . '/js/wptuts-social.js', array('jquery', 'socialite'), '', true );

	// Now enqueue Socialite
	wp_enqueue_script( 'wptuts-social' );

	// Register social CSS
	wp_register_style( 'wptuts-social', get_template_directory_uri() . '/css/wptuts-social.css');

	// Now enqueue social
	wp_enqueue_style( 'wptuts-social' );

add_action( 'wp_enqueue_scripts', 'wptuts_load_socialite' );

Point to Ponder

Make sure you change the sprite image path to your own server. You can download the image below and upload it to your blog and then swap its location at line #7 in the above CSS code.


Step 4 HTML Markup

Let’s see the HTML code for these buttons


Things to do here:

  • Change twitter-username-here with your own Twitter username in the code above.

Where to Add This Code?

This code can be added to a lot of places by a lot of methods. Let me give you some examples

You can add this code:

  1. Below the post meta in your single.php
  2. Below the content in your single.php
  3. In your index.php inside the loop etc.

Step 5 Adding HTML to WordPress

Manual Method

Go to your wp-content/themes/your-theme-folder/ folder, and open your single.php file. Then find the_content, and you will find some code like this . Add the HTML code shown next below it or above it.

Adding Before a Post

Go to your wp-content/themes/your-theme-folder/ folder, and open your functions.php file. Add the below code at its end:

function social_before_the_content( $content ) 
	$custom_content = '

';
	$custom_content .= $content;
	return $custom_content;

add_filter( 'the_content', 'social_before_the_content' );

Adding After a Post

Again Go to your wp-content/themes/your-theme-folder/ folder, and open your functions.php file. Add the below code at its end:

function social_after_the_content( $content ) 
	$custom_content .= $content;
	$custom_content .= '

';

	return $custom_content;

add_filter( 'the_content', 'social_after_the_content' );

Screenshots

Let’s take a look at these lazy loading social sharing buttons:

Before Hover

This is how the social icons look when the page first loads

before hover

After Hover

When you hover over them, the buttons load their files to become like shown below

after hover

Final Words

Tip: Be creative, don’t just copy / paste the code above and put it on your blog, try to give it a new look. Let the creative juices flow!

Some Examples

How Do I Use Them?

You can see the image below from my blog, how I use them. (Inspired by Mashable) (Live View)

Freakify.com | Learn How to Blog Like a Pro

Original from: http://wp.tutsplus.com/tutorials/add-lazy-loading-social-sharing-buttons-to-your-wordpress-blog/

How to Analyze Your WordPress Installation’s Performance

August 28th, 2012 Comments off

Installing WordPress is really easy. Optimization is what takes time. Not everyone who owns or maintains a WordPress website on their own is a programmer. Many WordPress users do not even know HTML. You may buy hosting from the best hosting provider but there are few things that need to be checked for maximum performance. This tutorial is not about optimization or setting up caching plugins. Those topics have been covered in the past. Today we will learn about plugins that could help us analyze the performance of a WordPress website to understand the problem areas and see their impact on the website.


WordPress is a complex piece of software. There are lot of things going on in the background that are required to load a page. Directly installing a caching plugin will definitely speed up the site a bit, but understanding how your active theme and plugins are performing would give you more insights and enable you to fix them and make your website perform at its peek. Before we talk about the how to analyze, let’s talk about what affects the performance.

Some of the factors affecting the performance of a WordPress site are:

  1. Errors in the theme and plugins
  2. Outdated code
  3. Number of database queries
  4. Lots of file requests
  5. Slow server

Most support tickets on WordPress.org forums are related to things not working properly. Plug-ins seem to cause the most number of issues. Unlike themes in the WordPress repository, plugins are not rigorously tested by a review team. They’re looked over by one of a handful of people, but it’s a cursory check for security / spam issues, not quality. Once approved, users directly upload their new plugins or updates and then users using those plugins are able to update it on their own site. If the plugin has a bug, it results in your website showing some errors or not loading at all. An often suggested solution when something like this occurs is to de-activate all your plugins and then enable them one at a time to find the problem plugin.

Before we go further, let’s clear up two myths about plug-ins:

  • Plug-ins that are installed but not activated do not slow down or affect your website
  • How the plugins are coded affect your website and not how many plugins you have installed

Analyzing Performance of WordPress Website

To be able to analyze a WordPress website and the performance of the plugins, we are going to need a few plug-ins and some external services. For someone having a VPS or Dedicated Server and requiring more insights, you may use a paid service like New Relic that would allow you to measure the performance of posts, categories, tags and other content types and more detailed graphs. For the purpose of this article, we are only going to use the plugins and tools which are free to use.

1. Install the Tools We Would Need to Analyze Performance

Tip: 3 of the 5 plugins mentioned (and other good ones for development not mentioned) are installable through the Developer plugin released by the Automattic WordPress.com VIP team.

2. Edit Your wp-config.php File

Open your wp-config.php and change the value of constant WP_DEBUG to true and below it add define('SAVEQUERIES', true);

/**
 * For developers: WordPress debugging mode.
 *
 * Change this to true to enable the display of notices during development.
 * It is strongly recommended that plugin and theme developers use WP_DEBUG
 * in their development environments.
 */
define('WP_DEBUG', true);
define('SAVEQUERIES', true);

This would allow us to see any errors and get information about the database query performed on each page.

3. Test Your Theme for Errors

If your your theme has any errors which did not show up earlier, after defining WP_DEBUG to true some hidden errors if any might now show up. Before we move to WordPress related errors, it’s important that the theme does not have any major PHP Errors. Once all major errors are fixed, you could then test your theme based on the Theme Review guidelines set by WordPress.

Theme CheckTheme Check

If you have successfully installed the Theme Check plugin, then in the “Appearance” menu, you would find a “Theme Check” sub menu. The active theme is selected by default. If not make sure to select it and then click on the “Check It!” button. You are not required to follow every suggested recommendation, as some are simply marked as informational for you to consider, however it’s important that you follow WordPress’ standards in your theme as much as possible.

4. Check Website for Deprecated Calls

For best performance it’s necessary to keep your WordPress core, themes & plugins updated to the latest stable version. The “Deprecated Calls” plugin helps to identity any code in our theme or the installed plugins that use any deprecated function calls in WordPress. The plugin also suggests the latest equivalent of the function making it easier for developers to update their code. To access the plugin data, under the menu “Tools” click on the “Deprecated Calls” link.

Deprecated CallsDeprecated Calls

5. Use Debug Bar to Understand the Background Process

Debug BarDebug Bar

If you have the admin bar activated while visiting the front-end of your website, you should see a “Debug” link on the top. Click on it to display the debug information about that specific page of your website. This would allow you to quickly identify the number of queries performed to render a page in your website. Removing widgets, reducing the number of posts that are displayed, would help you in reducing the number of queries and load on the server. Debug Bar comes in handy also when analyzing which template in your theme is used to render a page/post and to also check the rewrite rules used.

6. Analyze Impact of Plug-Ins

To analyze impact of plug-ins on the overall website, we would use the P3 profile plugin. If you have already installed it, then under “Tools” menu, find and click on the “P3 Plugin Profiler” link. Click on the large blue “Start Scan” button and then choose the “Auto Scan” option to do the testing automatically. Now the plugin will load each page on the website and analyze how much time it takes to load WordPress and the plugins. Once the scan is complete, you would see a “View Results” button. Click on the button.

P3 Plugin ProfilerP3 Plugin Profiler

Using the data in the result you should now be able to understand and compare the impact of each plugin on the overall load times. Using advanced settings you can also change the test IP & log the last 100 visits.


Quick Tips on Improving Your Website’s Performance

1. Fix Errors & Avoid Use Any Deprecated Functions

Fixing errors is the most important process of a website optimization.

2. Reduce MySQL Queries

The number of posts and other items displayed on each page of your website affects the load time. Reducing the number of posts, custom post types and widgets displayed on each page will reducing the number of queries and will have direct results in the speed of your website.

3. Reduce Number of HTTP Requests

Only a certain number of simultaneous connections can be made between your browser and a host at a time. Using tools like Pingdom Tools or GTmetrix, you can understand how your website is loaded. Combine icons and other smaller image files into a single file also known as a sprite and then display them using CSS background position. You can also combine multiple CSS or JavaScript files together which will further reduce the number of HTTP requests, helping speed up the website.

Pingdom

4. Use Asynchronous Script or Content Loading Wherever Possible

Asynchronous loading of scripts such as Google Analytics, or any other script would allow the website to load first without waiting for this file. Currently the widest use of this is for large image galleries wherein only the images displayed in the top section of the website visible to the user are displayed and other images further along the page are loaded when the user scrolls the page.

5. Use Only Absolutely Necessary Plug-Ins

Deactivating unnecessary plugins can also help to speed up the website. Number of active plugins isn’t an accurate measure for the affect on the speed of a website. Like I mentioned earlier, how the plugins are coded would affect the speed. WordPress is a community driven project. If you find a bug in a plugin, it’s important that you to go the plug-in’s page on the WordPress repository and mark that it does not work, and file a bug report in the forum. This helps other users become aware of any issues without having to install and check themselves.

6. Use a Caching Plugin

Once you have fixed all errors and optimized your website manually, the last step is to use a caching plugin like WP Super Cache or W3 Total Cache. I personally refer W3 Total Cache however it’s advised that you try both and chose the one you are comfortable with. These plugins provide the option to combine multiple CSS/JS files into a single CSS/JS file and minify them to decrease their size reduce load times.


If there are any tools or plugins that you personally use to analyze your WordPress website’s performance then please share with us in the comments. Always remember to fix any errors in your theme before using any caching plugin. Working in steps would allow you to solve errors earlier in the development of a website.

Original from: http://wp.tutsplus.com/tutorials/scaling-caching/how-to-analyze-your-wordpress-installations-performance/

Quick Tip: A Workaround for Hard Cropping Featured Images

August 17th, 2012 Comments off

This quick tip explains how to add a Custom Column in the Manage Screens of your WordPress blog.


Recently, I found myself needing to start using featured images instead of timthumb.php for the first time. Everything was great except that I found it really annoying that I was unable to specify exactly what size an image should be (hard-crop).

After looking around for a while, I found that most people’s solution was to use a plugin which ended up having an excessive amount of code in it.

Additionally, I wanted to be able to serve a responsive layout using the Skeleton grid system class of “scale-with-grid” – the original reason for using featured images which doesn’t require a front end width and height attribute.

Here’s the workaround that I came up with given the requirements of the project.


Step 1 Apply an Arbitrary Class to Your Featured Post Images

We need to be able to have control over the image using our stylesheet so we need to apply a class that only affects the image itself. I chose just to wrap my image in a figure/div called ‘headline‘. That was in addition to a custom post thumbnail size that I had already set in the functions.php file called ‘huge‘ – this thumbnail size had a maximum width of 940 while the height was 900.

That’s fine assuming you want an image with a height of 900px – but let’s face it: you probably don’t because it looks like this:

Here’s the code I wrote for the template:

	
'scale-with-grid')); ?>

Step 2 A Little Bit of CSS Hackery

	#headline 
		max-height: 400px;
		overflow: hidden;
	

And after we’ve added that code we get the following result which is much more manageable:


Why It Works

This works because we only set a maximum-height and not a maximum-width. WordPress defaults to the maximum width which we set via our function:

	add_action( 'init', 'my_register_image_sizes' );

	function my_register_image_sizes() 
		add_image_size( 'huge', 940,900, true );
	

The image is technically still all there in its full size but we caused the browser to hide anything over the height of 400px by using the overflow: hidden attribute.

It works!


Just One Problem Though…

While it looks good, we’re actually hacking wildly at our browser here. Remember that the image only looks as if it has resized – as we’ve already said the image is still there in full.

That means that despite it looking great all the way down to mobile, it’s actually taking up kind of a lot of space.

Does anyone have a better solution? Leave your ideas in the comments below!

Original from: http://wp.tutsplus.com/articles/tips-articles/quick-tip-a-workaround-for-hard-cropping-featured-images/

Admin Panel Post Column Management

July 29th, 2012 Comments off

We will build a plugin to look at using the available filters and hooks to change the admin panel post columns. Add, delete and populate them with content.

When thinking of WordPress development, the most common things I find that come to mind are theme and plugin functionality and implementation to make a simple idea work and look the way you want it to. With a backend page and some or a lot of settings here and there.

WordPress API flexibility goes way beyond the things that you might have been familiar with.


Step 1 The Plan

Before we even start doing anything, we must understand what we are going to accomplish, what our final result is going to be. We are going to build a plugin that is going to manage admin panel post columns and their content. To build a plugin we need an idea that will fit our needs, so for this tutorial our plugin is going to slightly turn the posts functionality into a very simple price and currency management interface. To be even more specific, we are going to:

  • Add 3 items in the post edit page as a meta box, those 3 items will be a price box, a quantity box and a currency radio button
  • We are going to make that meta box function
  • The items will be saved as custom posts for easier management later
  • Add 4 columns in the posts page list in the admin panel with the price, currency, and quantity, also an extra field, picture
  • Get the values of each of the previous columns and post them accordingly
  • Show the featured image of the post in the picture column content

And that’s it, in a nutshell, everything that this tutorial is about. Again, we are talking about implementing this in the admin panel post management pages only. As part of the plan, it is implied that you know how a basic WordPress plugin is created and works, but still, I am going to mention that we are going to create a directory in the plugins folder of WordPress by the name of productA and a file inside it called productA.php. I guess it’s obvious now that our plugin is named Product A, I think that is a good name for a simple plugin with the above features for the purposes of this tutorial.


Step 2 Plugin Headers

This is a fun easy part, creating the first most necessary parts of the plugin, namely the stuff that identifies it to WordPress as a plugin and runs the file in order for our plugin to function properly. So we go ahead and create our Plugin Name, plugin Description, Author name and plugin Version header values that are commented at the top of the plugin file source code, just like in the following example:



Step 3 Implementing Required Actions and Filters

The first thing that we are going to do is to add the meta-box functionality in our plugin. We want to add a custom made metabox in our edit post page, somewhere at the top of the right sidebar. In order to do this we must create an action (or hook) the functionality of which we will take care of a little later but let’s see how the hook is called and implemented in this step first:

The Meta Box Hook

function pA_admin_init() 
	add_meta_box('pA_metaid', __('quantity/price', 'pA_textdomain'), 'pA_inner_custom_box', 'post', 'side', 'high');

add_action('admin_init', 'pA_admin_init');

First we add a new action at the bottom of our file that we are going to use for a first parameter, the action tag of admin_init in order to call this function whenever a user accesses the admin area. The second parameter is the callback function name that is to be implemented when the hook is activated. We are going to call this function pA_admin_init and it looks like the above.

The pA_admin_init function contains the method that creates the meta box we need, generated by the function add_meta_box with the following variables:

  • pA_metaid – for a unique identifier of the meta-box
  • __('quantity/price', 'pA_textdomain') – a string that represents the title of the meta-box
  • 'pA_inner_custom_box' – the callback function
  • 'post' – a string representing the post type (because we are working on posts, we are going to set the string value to ‘post
  • 'side' – a string representing the screen position of where we want our meta box to be on, we can use ‘normal‘, ‘advanced‘ or ‘side‘. We are using ‘side‘ as we want it to show on the right side of our content
  • 'high' – the position amongst the other meta box elements of the page content side

This would be pretty much it for the first step of the meta-box action.

Saving the Meta Box Post Data Hook

At some point the data introduced into the meta box needs to be saved, in order to save it we need to add another hook to the list, this time with a different, specific tag as a first parameter.

add_action('save_post', 'pA_save_postdata');

The above example implements the much needed hook. As you can see, the tag parameter used in this case is save_post in order to get to the point where the post is submitted, all the form elements are sent to PHP and saved in the database, so that we can save our data exactly when the form is submitted and WordPress processes it. The callback function that does all the work is named pA_save_postdata, we will create this function a little later in the tutorial when we will take care of all the aspects of the meta box.

Working With the New Column Post Data

Because we are trying to create extra columns in our post page list we must populate the rows with the data of those new columns. To do this we are going to use the following code:

add_action('manage_posts_custom_column', 'pA_manage_posts_custom_column', 10, 2);

The tag used is manage_posts_custom_column and the callback function pA_manage_posts_custom_column, function that we are going to build in a few moments.

Column Filter

Last but not least, we want to add and remove a few columns from the posts page list. To do this we must filter the existing ones and remove or add as we wish by calling a filter like in the next example:

add_filter('manage_posts_columns', 'pA_manage_posts_columns');

The filter, just like the actions has main parameters that we use, one is the tag, in this case a string by the name of 'manage_posts_columns' and a callback function, also as a string but with the name of 'pA_manage_posts_columns'. We are building and using this function in one of the next steps.


Step 4 Meta Box

As we want to create a meta box and we already set the hooks and functions to get to a callback method that generates it, we need to write the code for it.

First we are going to take a look at the pA_inner_custom_box function. This function has very basic code inside it that generates and manages a form with data. First, there are 3 variables $pA_price, $pA_quantity, and $pA_currency to hold the values of our 3 elements we want to insert in the meta tag and posts list. To do this, we are going to get them from the custom fields where we are going to save them next in the save_post action. Then we create the HTML form fields that we are going to use to post the data when the post is updated or published, again, using the save_post callback function action. All this code is available fully here:

function pA_inner_custom_box() 
	global $post;

	$pA_price = get_post_meta($post->ID, 'pA_price', true);
	$pA_quantity = get_post_meta($post->ID, 'pA_quantity', true);
	$pA_currency = get_post_meta($post->ID, 'pA_currency', true);
	?>
	


currency: type="radio" name="pA-currency" value="USD" />USD / type="radio" name="pA-currency" value="GBP" />GBP / type="radio" name="pA-currency" value="EUR" />EUR

Now, firstly, why are we using custom fields? For easy management and for any future easy sorting, filtering inside the posts query. Second, we are using two textboxes for each of the price and quantity values and radio buttons with USD, GBP and EURO options for the currency values. Each of these form elements are given the values of the variables that we previously filled with values from specific custom fields.

That’s it for this part, when the user updates or publishes a post these values will be sent to the next callback function of our tutorial.

Saving the Submitted Data

The second and very crucial part of the meta box functionality is saving the data we are submitting. At the beginning of the tutorial we implemented a function that manages the post submitted data. Now we are going to take a look at how its callback function works.

First, because we need a way to identify the post we need to include the global variable $post in order to get the id value of the currently submitted post. Then we will check if a hidden variable that we created as a form element was submitted or not. If it was submitted, we start extracting the values of custom fields from the database for each element we are interested in: price, quantity and currency. We will use the get_post_meta function to get the custom field meta key values using the $post->ID variable value as an identifier and the meta key name that we are interested in. We need these values to set the previous value parameter in our next piece of code from this function that handles the data update.

The data is saved as custom fields under a specific metakey name pA_quantity for quantity, pA_price for price and pAcurrency for currency values. The new data is extracted from the $_POST variable that contains submitted data.

function pA_save_postdata() 
	global $post;
	if ($_POST['pA-hidd'] == 'true') 
		$pA_price = get_post_meta($post->ID, 'pA_price', true);
		$pA_quantity = get_post_meta($post->ID, 'pA_quantity', true);
		$pA_currency = get_post_meta($post->ID, 'pA_currency', true);

		update_post_meta($post->ID, 'pA_quantity', $_POST['pA-quantity'], $pA_quantity);
		update_post_meta($post->ID, 'pA_price', $_POST['pA-price'], $pA_price);
		update_post_meta($post->ID, 'pA_currency', $_POST['pA-currency'], $pA_currency);
	
}

This concludes the meta box implementation in our plugin.


Step 5 Filtering Posts Columns

Finally we have reached the main part of this tutorial, well, at least one of the main parts. I say main parts because this next thing is what the tutorial is all about, still, it cannot function without all the other parts previously done. We are going to take a look now at how to remove and add new post columns to the posts page in the admin panel.

Because we have extra values especially added to the post, things like price, currency and quantity, we want in this part to have extra columns in the posts page with these names and the related values. Let’s clean things up a bit, first, we want to remove author, tags and comments from the columns as for the purpose of this tutorial we want to learn how to do this and we do not need those columns since we are trying to act like the posts page handles a product with things like price and quantity.

function pA_manage_posts_columns($columns) 
	global $wp_query;
	unset(
		$columns['author'], $columns['tags'], $columns['comments']
	);
	$total = 0;

	foreach ($wp_query->posts as $post) 
		$total += get_post_meta($post->ID, 'pA_price', true) * get_post_meta($post->ID, 'pA_quantity', true);
	

	$columns = array_merge($columns, array('price' => __('price'), 'currency' => __('currency'), 'quantity' => __('quantity'), 'featured_image' => __('Image'), 'total' => __('Total: ' . $total)));
	return $columns;
}

Looks simple enough, right? I’m of course talking about the above callback function for the manage_posts_columns filter tag that handles the management of post columns, just like the name says. There are just a few lines of code there but this part is actually more complicated than any previous part in this tutorial (and those parts are not that hard so this one should not be that hard to understand either).

Firstly, the callback function of the previously mentioned filter has a parameter that holds all the columns inside it as an array. We are setting this parameter under the name $columns so that we can use it in a few moments. Next we need to integrate a global variable into the function, namely $wp_query. We are also going to use this shortly.

Removing Columns

Since the $columns parameter is an arrray that contains all the columns of the posts page, all we have to do in this case is remove the array parameters that we wish. To do this, we just use the unset PHP function and we separate the array names that we want to remove by commas. Easy.

Calculating Totals

Because we are using price and quantity as values that we are working with dynamically, we want to make a total of those values in a special extra row that we will add in a moment. To calculate this, we need to extract the values of all the prices and quantities of each post, multiply them and add the results up. The result will be a total of all the posts item values multiplied by their quantity. The sum of this we want to post in the title of the column when we add the column on the next part. So we retrieve the values of the price and quantity custom fields of each post using the get_post_meta function, and make a total using an incremented $total variable. To create the loop with our required data we will use the integrated $wp_query global variable.

Adding Columns

To add columns, we are going to use the approach we used in removing them only in a different way, namely not the unset function for removing but the array_merge PHP function for adding the new columns. The columns are added as arrays in this order and by these names: price, currency, quantity, featured image and Total.

All that’s left to do now is to return the $columns variable and the callback function will do its magic. The end result is something that should make the posts page have the head table titles look like this:


Step 6 New Columns Data

The final step of this tutorial is about the custom column values. After creating the columns previously we need to show the values of those prices, currencies and so on, in the posts list we need to add the corresponding values of the custom values to the list properly. To do this we are going to use a previously implemented hook that has the callback function with the name of pA_manage_posts_custom_column. The function has two parameters, a column parameter containing the name tag of the column we are in, used by us to identify where we are, and the post ID as a second parameter.

First we need a switch condition to check the $column variable for what type of post we are in. Of course, we are interested only in our custom created columns, so we will put the cases only to those values.

Price, Currency and Quantity

These three column types that we created have a common meta key data type, a simple string that is a custom column that we can get by using the get_post_meta function with the appropriate variables, more precisely $post_id for identifying the post, meta key for identifying the custom field and a boolean variable set to true for getting the data as an echoed string or as an array.

There is one extra column that we added that is a little different and not really mentioned previously. I am talking about the featured_image column that will show the featured picture’s HTML tag from the the post inside the row of the current post. To get the featured image we are using the get_post_thumbnail function with the post id as an identifier and a size string.

One last column value is the total. The total of each post is calculated by extracting the custom fields using the same method as before (get_post_meta function) of price and quantity and multiplying them. The total is the result we are looking for.

function pA_manage_posts_custom_column($column, $post_id) 
	switch ($column) 
		case 'price':
			$pA_val = get_post_meta($post_id, 'pA_price', true);
			break;
		case 'currency':
			$pA_val = get_post_meta($post_id, 'pA_currency', true);
			break;
		case 'quantity':
			$pA_val = get_post_meta($post_id, 'pA_quantity', true);
			break;
		case 'featured_image':
			if (has_post_thumbnail())
				$pA_val = get_the_post_thumbnail($post_id,'thumbnail');

			break;
		case 'total':
			$pA_price = get_post_meta($post_id, 'pA_price', true);
			$pA_quantity = get_post_meta($post_id, 'pA_quantity', true);
			$pA_val = $pA_price * $pA_quantity;
			break;
	
}

The above example is the way the function we discussed previously should be implemented to work properly, you can check the above code to understand this section of the tutorial. As a visual result, the hello world post was given a few values for price, currency and quantity and a random print screen was uploaded as a featured image. With our plugin installed the posts admin page looks like this:


Conclusion

WordPress is becoming more and more powerful and flexible with lots of new features and posibilities that not only we did not have but we might not even realise how useful they are. This tutorial has the purpose of helping you understand how you can easily manage columns for posts in the admin area. You can choose to use this information how you wish for any project you might think of that would make it useful. Just think of the possibilities you can create with these simple steps!

What are some other underrated WordPress features you think people often overlook? Let us know in the comments!

Original from: http://wp.tutsplus.com/tutorials/creative-coding/admin-panel-post-column-management/

Creating an Ajax Countdown Timer WordPress Plugin

June 6th, 2012 Comments off

Building a WordPress plugin is not that hard, especially when you know what you’re doing. Sometimes it can get tricky though when working with multiple scripts, styles, and new functionality that sometimes requires some imagination.

In this tutorial we are going to look at a way to create a simple countdown timer plugin. We’ll look at integrating it into the WordPress installation as a widget and a shortcode in the content using settings from a meta box inside the WordPress admin editor.

A preview of the end result of this tutorial looks like this:

The Widget and Content Shortcode:

Widget and Meta-Box Admin Interface:

A short example screenshot of how the widget admin and meta box in the edit page/post interface will look like at the end of the tutorial:


Step 1 Plugin File Headers

Each WordPress plugin mush have compatible, up to date code in its headers, so that it can function and be recognised by WordPress. This allows it to be installed, activated and removed. The kind of information that is available in the header information is crucial for the plugin but also contains information about it like title, version, description, tags, author info, license, etc.

First, the plugin is a file placed in a directory. We are going to name our plugin Timer Plugin and place it in our wp-content/plugins folder under the directory timer_plugin. Then inside that, the file timer_plugin.php will be our main plugin file where we insert the header source code.


We are just going to use the basic variables needed to get the plugin up and running. One of the variables is the Plugin Name, that is very important in order to identify the plugin in the plugin installation page. For the purposes of this tutorial we are just going to name it Timer Plugin. Next, the Description that is a short line of text describing the plugin. That will also be visible under the plugin installation page right next to the plugin, along with the next variables, the Author and Version.

“All header plugin variables are strings of text written after the : preceding the header variable names.”


Step 2 Adding Actions

In WordPress, actions are hooks to specific functions that you might want to use in your functionality. In this tutorial we are going to use a number of hooks to get the desired result.

First, the actions are going to be added using the add_action function for each action, and we are going to add them at the end of the PHP file as the next example:

add_action('widgets_init', 'TP_widgets_init');
add_action('admin_print_scripts', 'TP_admin_register_scripts');
add_action('admin_print_styles', 'TP_admin_register_styles');
add_action('wp_print_scripts', 'TP_register_scripts');
add_action('wp_print_styles', 'TP_register_styles');

Next, in the above example, the wp_print_scripts and wp_print_styles hooks add actions to functions that are used to register and include the styles and scripts needed in the WordPress front end. More precisely in the website theme, for the functionality of the sidebar widget timer and the content shortcode. The admin_print_scripts and admin_print_styles hooks are used to register the WordPress admin panel script and CSS style files used later on in the tutorial.

add_action('admin_init', 'TP_admin_init');
add_action('save_post', 'TP_save_postdata');

Finally, the admin_init hook pointing to the function that runs before the headers are generated and run. A hook that we will cover at the end of the tutorial is save_post. This hook is required to work with the post or page submitted information in WordPress admin.

“For more detailed information on how to use the add_action function see Add_Action in the WordPress Codex.”


Step 3 Registering and Including Scripts and Styles

For this tutorial we are going to require a number of script and style files that are required for good functionality and look on both the admin and the theme implementation of the Timer Plugin. Here is how we are going to do this:

Including Styles for WordPress Admin Functionality:

The Timer Plugin requires a few elements in the admin panel that we will need to style slightly as the default look is not exactly very welcoming. In order to do this we have called in step 3 the tag hooks that help us do that, now we are going to look at the functions that run when the hooks are called and how they work exactly.

First, the TP_admin_register_styles function for the registered and included admin panel styles.

function TP_admin_register_styles() 


Downloading the Styles

Because we are building a countdown timer plugin, we require a specific date and time to countdown to from the present. To do this, amongst other integrations, we are using the wp_register_style function to register the latest custom jQuery UI style so that we may use its design properly in its functionality when generating the sliders and calendar date picker later. The CSS file is generated by downloading the latest jQuery UI from http://jqueryui.com/download selecting Core, Widget, Mouse, Slider, DatePicker from the list of options, jQuery Ui 1.8.20 in the version section, and UI Lightness in the theme dropdown section.

Registering the Styles

There will be a CSS file named jquery-ui-1.8.20.custom.css and an images folder inside the css/jquery-ui folder in the custom generated and downloaded archive that you will get from the previous instructions. We are going to replace the jquery-ui-1.8.20.custom.css file name to jquery-ui.css for a friendlier name and copy it alongside the images folder with all its files in our plugin folder.

After that we can start adding the registration and inclusion functions inside the TP_admin_register_styles function mentioned previously.

	// register
	wp_register_style('jquery-ui-theme', plugins_url('jquery-ui.css', __FILE__));
	wp_register_style('tp-admin-style', plugins_url('admin-style.css', __FILE__));

The previous example uses wp_register_style to register the jquery-ui.css file by the name of jquery-ui-theme that is later used in the wp_register_style function in the next example. The same approach is used to include the main admin style.css file using this time the name tp-admin-style used in the following examples with the wp_enqueue_style function to include it in WordPress headers properly.

Including the Styles

	// enqueue
	wp_enqueue_style('jquery-ui-theme');
	wp_enqueue_style('tp-admin-style');

The tp-admin-style is used to register and include the style.css file that will be used for styling the widget and meta-box design that comes by default in the jQuery UI implementation and WordPress default style.

Including Styles for Theme Functionality:

Using the exact same approach as before for registering and including style files we are going to include into the WordPress theme the style files necessary for the design of the widget timer and the shortcode.

function TP_register_styles() 
	// register
	wp_register_style('tp-style', plugins_url('style.css', __FILE__));

	// enqueue
	wp_enqueue_style('tp-style');

In this case we are including a simple style.css file from our plugin directory that we will include later.

Including Scripts for WordPress Admin Functionality:

Because we are going to build a widget and a meta box with jQuery UI calendar and date time picker functionality, we are going to have to have jQuery, jQuery UI and all the plugins necessary to include and use the slider and datepicker that we will implement later. To do this, we have to make use of the previously written action for the admin_print_scripts hook. The next function will implement the functionality we need.

function TP_admin_register_scripts() 
	// register
	wp_register_script('tp-admin-script', plugins_url('admin-script.js', __FILE__));
	// enqueue
	wp_enqueue_script('jquery-ui-core');
	wp_enqueue_script('jquery-ui-datepicker');
	wp_enqueue_script('jquery-ui-slider');
	wp_enqueue_script('tp-admin-script');

As we are working inside the WordPress admin panel, we are going to have jQuery and jQuery UI already registered and included in the header, as well as the dependencies and plugins we need: jquery-ui-mouse and jquery-ui-widget. All we are including now is the jquery-ui-core that is not included by default and the datepicker and slider plugins that we need and last, the admin-script.js file that contains all the custom rules for our date-time jquery-ui functionality.

Including Scripts for Theme Functionality:

We need to be able to have inside the front end of the website, a timer that decrements to 0 somewhere in the sidebar as a widget and in the content as a shortcode. As a very easy way to do this, I chose jQuery and some plain javascript to work the timer. As a result we are going to include the script.js file inside the function that registers scripts for the front end hook previously declared.

function TP_register_scripts() 
	// register
	wp_register_script('tp-script', plugins_url('script.js', __FILE__), 'jquery');

	// enqueue
	wp_enqueue_script('tp-script');

We are going to also specify jQuery as a dependency as the front end does not have it included by default.


Step 4 Creating the Widget

The plugin is supposed to use a widget as one of the two methods to integrate a timer into the theme, more specifically, the sidebar in this case. To be able to add the timer to the sidebar we need to implement widget functionality for our plugin into WordPress.

Building the Class

To implement widget functionality in the plugin, we must include a widget class named TP_Widget. This name is of course not mandatory but it is mandatory for this class to extend the WP_Widget class in order to inherit its functionality. Therefore we create the class like the next example:

class TP_Widget extends WP_Widget 
	// the following code will be here

Next comes the code we add inside the class so that we work with the widget the way it’s intended to in WordPress, using all the necessary functions that are required in order to have a functional widget created in WordPress.

First we are going to write the __construct function for the initial required code integration. The __construct function is the place where the widget actually processes. We are going to give the widget a name and description inside this function by inheriting and using the parent’s __construct method like in the following example:

	public function __construct() 
		// widget actual processes
		parent::__construct('TP_Widget', 'Timer Widget', array('description' => __('A Timer Plugin Widget', 'text_domain')));
	

The first parameter is a widget ID, second is a widget name, third an array with the description. The following function is going to be the form function. We are going to build and use this function to set and work with the admin panel widget content form. The next code will run inside the widget placeholder in the admin panel widgets page:

	public function form() 
		if (!$_POST) 
			$tp_arr = unserialize(get_option('tp_ID_' . $this->number));
		
		else 
			if ($_POST['tp-hidd'] == 'true') 
				$tp_arr['tp-title'] = $_POST['tp-title'];
				$tp_arr['tp-date'] = $_POST['tp-date'];
				$tp_arr['tp-hour'] = $_POST['tp-hour-val'];
				$tp_arr['tp-minute'] = $_POST['tp-minute-val'];
				update_option('tp_ID_' . $this->number, serialize($tp_arr));
			
		}
		// outputs the options form on admin

In this part we have widget information like Title, Date, Hour and Minute. This information is extracted from a serialized array string that is stored into the database by the name tp_ID_X, where X is an unique identifier of the widget, used to identify the data being extracted relative to the widget used.

In this part the widget values are also stored into the array one by one, serialized and stored in the database as an option field for later use.

The next part is the admin widget form elements that are used in the front end.

	


[ Edit ]


There are two aspects to look after in this particular section:

First, the tags classes like tp-date, tp-hour, tp-minute that are later worked with in javascript and second, the input fields. Firstly, there is some PHP code inserted in the input fields that exist in the code above, code that is used for storing data either for forms in order to be submitted, or for javascript to be implemented into jQuery and worked with.

At the end of the HTML code above the form function is closed.

Updating the Widget Data

When the widget Save button is pressed in the admin panel, the form information is submitted and processed by the following function:

	public function update() 
		// processes widget options to be saved
		if ($_POST['tp-hidd'] == 'true') 
			$tp_Arr['tp-title'] = $_POST['tp-title'];
			$tp_Arr['tp-date'] = $_POST['tp-date'];
			$tp_Arr['tp-hour'] = $_POST['tp-hour-val'];
			$tp_Arr['tp-minute'] = $_POST['tp-minute-val'];

			$tp_Arr['tp-date'] = $_POST['tp-date'];
			update_option('tp_ID_' . $this->number, serialize($tp_Arr));
		
	}

The update function is the function used to update the information in the widget in WordPress widgets.

Writing the Widget Output in the Sidebar

This next part is the code that generates and outputs the widget in the sidebar as a widget. Basically it is the contents of the already generated widget code that has the purpose of a compatible wrapper.

Here is an example of just half of the function, namely the PHP code that is used to get the required information for the widget output.

	public function widget($args, $instance) 
		$tp_arr = unserialize(get_option('tp_ID_' . $this->number));
		$temp_date = explode("/", $tp_arr['tp-date']);
		$tp_arr['tp-date'] = $temp_date[2] . "/" . $temp_date[0] . "/" . $temp_date[1];
		extract($args);
		$title = apply_filters('widget_title', $tp_arr['tp-title']);

		echo $before_widget;
		if (!empty($title))
			echo $before_title . $title . $after_title;

So we are extracting the widget data previously saved in the admin panel. The next part is the HTML and PHP code that represents the timer and/or has the values used later by jQuery to calculate the time and function as a timer.

	
:0" />
      YY
      DD
      HH
      MM
      SS
  • -
  • -
  • -
  • -
  • -

The UL tag is used to create later on a row and column style so that the timer has an ordered look and is given a class in order to easily control the LI tags with jQuery later on.

Also, you may notice the input elements with PHP data in them. Those elements are also used by jQuery to store the values of the saved date and time.

The function is ending after the HTML code with a dynamic variable that closes the widget using WordPress compatible values.


Integrating the Class

Last but not least, if you remember, one of the actions written in step 1 was using the widgets_init tag and pointing to the TP_widgets_init function. We need to write its functionality in order to link the class properly to WordPress.

function TP_widgets_init() 
	register_widget("TP_Widget");

“For a more extensive look of the standard WordPress widget functionality check out WordPress Widget API


Step 5 Creating the Meta Box

The meta box is a box located in one of the sidebar panels located in the admin editor of any page or post. Because we are using almost the same HTML, CSS and JavaScript code we are going to use almost the same PHP and HTML code as the widget. Some modifications of some parent element classes are required for jQuery functionality. But first, the meta box must be created and implemented into WordPress from the plugin settings. Another one of the actions written in Step 1 that we did not finish implementing is the admin init hook tag. That hook runs before headers take place and is going to be used by us to implement the meta box functionality with the add_meta_box function like the example below:

	function TP_admin_init() 
		add_meta_box('TP_metaid', __('Timer Plugin Post Settings', 'TP_textdomain'), 'TP_inner_custom_box', 'post', 'side');
		add_meta_box('TP_metaid', __('Timer Plugin Page Settings', 'TP_textdomain'), 'TP_inner_custom_box', 'page', 'side');
	

What this code does is it creates a custom box on the side of each post and page edit page in the admin panel with the content and functionality of the function TP_inner_custom_box. For a more comprehensive view of how add_meta_box should be used, see add_meta_box in WordPress Codex.

Functionality and Front End Code

The meta box has a similar front end with the widget and the back end code is not that different, just slightly different database option field names to save in. Just like the widget admin form it is made out of both PHP and HTML functionality. Starting with the TP_inner_custom_box function we are creating the meta box admin front and back end functionality like the next sample:

	function TP_inner_custom_box() 
		global $post;
		// Use nonce for verification
		wp_nonce_field(plugin_basename(__FILE__), 'cuschost_noncename');
		$tp_arr = unserialize(get_option('tp_pp_ID_' . $post->ID));

After that, the HTML code sample is strikingly similar. The only differences are an extra input button after which, the function is enclosed with the semicolon and ends.

	[ Edit ]


Saving the data

The previous form sends data when the post or page is updated, and we need to get that data and store it for later user. In order to do that we use another hook that we already implemented, mainly the save_post hook tag that points to the callback function TP_save_postdata. The callback function gets the data from post variables and stores it into the database under a post ID unique identifier formed name and it looks like this:

	function TP_save_postdata() 
		global $post;
		if ( $_POST['tp-hidd'] == 'true' ) 
			$tp_arr['tp-date'] = $_POST['tp-date'];
			$tp_arr['tp-hour'] = $_POST['tp-hour-val'];
			$tp_arr['tp-minute'] = $_POST['tp-minute-val'];
			update_option( 'tp_pp_ID_' . $post->ID, serialize( $tp_arr ) );
		
	}

Step 6 Implementing the Shortcode

To implement the shortcode we need to add a new action to the add_action function list. The next sample is going to cover it:

add_shortcode('tp-shortcode', 'tp_shortcode');

It goes without saying that we must create the tp_shortcode function that handles the new shortcode.

	function tp_shortcode($atts,$content="") 
		global $post;
		$tp_arr = unserialize(get_option('tp_pp_ID_' . $post->ID));
		$temp_date = explode("/", $tp_arr['tp-date']);
		$tp_arr['tp-date'] = $temp_date[2] . "/" . $temp_date[0] . "/" . $temp_date[1];
		return '
      YY
      DD
      HH
      MM
      SS
  • -
  • -
  • -
  • -
  • -
';

Familiar code? It’s the front end for the sidebar widget code used previously in the widget function inside the TP_Widget class.

“For more detailed information on how to use the add_shortcode function see add_shortcode in the WordPress Codex.”


Step 7 Editing the Style Files, Styling the Timer

This is a very easy and quick step as it covers just 2 small files that handle the design of the timer widget, shortcode and admin section.

The Admin Section:

In this section the style file added in step one we are going to edit now is admin-style.css and it should look like this:

.tp-hour, .tp-minute  padding: 0px !important; z-index:0; width:100px; margin:10px 0px 10px 0px; height:10px; 
.tp-hour-val, .tp-minute-val  font-weight:bold; font-size:16px; width:20px; 
.tp-time  margin-top: 10px; margin-bottom: 10px; font-size:12px; 
.widget .editable, .inside .editable  background-color:#FED22F; 
.widget .ui-slider-horizontal, .inside .ui-slider-horizontal  background:#FED22F; 

This stylesheet file handles the width, height, colors and position of the admin widget sliders and calendar jQuery UI popup when choosing hours and minutes from the front-end.

The Timer Front-End Style:

The style.css file is the CSS file that covers the design of the UL, LI, OL of the timer in the front end. See the next sample:

.timer-content  width:300px; 
.timer-main ul, .timer-content ul  float:left; display:inline; overflow:hidden; width:180px; margin:0px; padding:0px; margin-top: 0px; font-weight: bold; 
.timer-main ul.tp-head, #content .timer-content ul.tp-head  margin:0px; padding:0px; margin-top:20px; font-size:12px; 
.timer-main ul ol, .timer-content ul ol  float:left; display:inline; overflow:hidden; width:20px; margin:0px; padding:0px; margin-right:2px; text-align: center; border:1px solid #dcdcdc; padding:4px; background:#f0f0f0; 
.timer-main ul li, .timer-content ul li  float:left; display:inline; overflow:hidden; width:20px; margin:0px; padding:0px; margin-right:2px; text-align: center; padding:4px; border: 1px solid white; 

Some elements are floated, resized and positioned with margins so they will look as intended. A result of this style is the design in the next picture:


Step 8 Admin Widget and MetaBox Javascript Code

The admin Widget requires very specific jQuery functionality mixed perfectly with HTML classes for tags. All of the following code should be put inside the admin-script.js file.

jQuery(document).ready(function($)
	$('.tp-insert-shortcode').click(function()
		send_to_editor('[tp-shortcode]');
	);
	$('.tp-time-edit').live('click',function()
		$('.tp-date').datepicker(
			format:'m/d/Y',
			hourGrid: 4,
			minuteGrid: 10,
			position: 'right',
			onBeforeShow: function()
				$(this).DatePickerSetDate($(this).val(), true);
			
		});
		$('.tp-date').addClass('editable');
		$( ".tp-hour").slider(
			value:0,
			min: 0,
			max: 23,
			step: 1,
			slide: function( event, ui ) 
				$(".tp-hour-val" ).val(ui.value);
			
		});
		$( ".tp-minute" ).slider(
			value:0,
			min: 0,
			max: 59,
			step: 1,
			slide: function( event, ui ) 
				$(".tp-minute-val" ).val(ui.value);
			
		});
	});
});

In this example, after a jQuery initialization and a document load event all the code that works with the widget and shortcode is loaded for use.

Now, because the widget has ajax-loaded dynamic content in it all its content is invisible to jQuery unless used with a live action. For this purpose, a link with the class name of tp-time-edit and tag option javascript functionality of void(0) was created and when clicked, runs the live hook and makes all HTML tags in the event function call available.

Inside the callback function we are using the functionality needed to create the datepicker for the date textbox by using the tp-date CSS class.

Last but not least, actually at the beginning of the code lies the shortcode javascript functionality, more specifically the jQuery insertion of the tp-insert-shortcode CSS class value found in the input field inside the shortcode function previously written in Step 6. When the button with the class tp-insert-shortcode is pressed, it should add the [tp-schortcode] string value to the WYSIWYG editor.

“Very Important! jQuery UI requires classes in tag properties to be used for the sliders and datepicker plugins. It does not work with ID’s”


Step 9 Timer Javascript Code

This is the most important and slightly most hard to visualise at first sight piece of code in the entire tutorial as it is the part dealing with a lot of math.

This part is referring exclusively to the script.js file that holds the javascript source code dealing with the actual timer both on the widget part and on the shortcode part in the front end.

jQuery(document).ready(function($) 
	function start_by_parent(tp_parentClass)
		var tp_timer ='';
		tp_date=$(tp_parentClass+' input.tp-widget-date').val();
		tp_time=$(tp_parentClass+' input.tp-widget-time').val();

		tp_timer = setInterval("tp_set('"+tp_parentClass+"','"+tp_date+"','"+tp_time+"');", 1000);
	
	start_by_parent('.timer-main');
	start_by_parent('.timer-content');
});

The parent class handling the widget is timer-main, as for the shortcode the timer-content CSS class is used as a parent tag element that is used to affect the li tag elements containing the timer values for DD(days), HH(Hours), MM(Minutes) and SS(Seconds). The above implementation is a dynamic approach to both of them in jQuery after the values are sent to the calc_data function to handle all the math.

The tp_set function is actually using the calc_data method to calculate the values before it inserts them in the appropriate HTML tag elements. Here is the implemented tp_set method that needs to go inside the same file, script.js.

function tp_set(tp_parentClass,tp_date, tp_time)
	calc_data(tp_date, tp_time);

	jQuery(tp_parentClass+' ul').find('li:nth-child(1)').html(tp_years);
	jQuery(tp_parentClass+' ul').find('li:nth-child(2)').html(tp_days);
	jQuery(tp_parentClass+' ul').find('li:nth-child(3)').html(tp_hours);
	jQuery(tp_parentClass+' ul').find('li:nth-child(4)').html(tp_minutes);
	jQuery(tp_parentClass+' ul').find('li:nth-child(5)').html(tp_seconds);

	var tp_timer = setInterval('tp_set(''+tp_parentClass+'',''+tp_date+'',''+tp_time+'');', 1000 );
    clearTimeout(tp_timer);

Finally, one of the most important parts of this script file, the calc_data method, that calculates the number of seconds between the present and the user selected date and returns the appropriate values so that the timer shows the amount of time left until that date.

function calc_data(tp_date,tp_time)

	tempdate = tp_date.split("/");
	temptime = tp_time.split(":");

	var seconds=1000;
	var minutes=seconds*60;
	var hours=minutes*60;
	var days=hours*24;
	var years=days*365;

	var db_time = new Date(tempdate[0], tempdate[1]-1, tempdate[2], temptime[0], temptime[1], 00);
	var now_time = new Date();
	db_time = db_time.getTime();
	now_time = now_time.getTime();
	var tp_result = db_time-now_time;
	if(tp_result < 0) 
		tp_years=tp_days=tp_hours=tp_minutes=tp_seconds=0;
	
	else
		tp_years = Math.floor(tp_result/years);
		tp_days = Math.floor(tp_result/days)-(tp_years*365);
		tp_hours = Math.floor(tp_result/hours)-(tp_days*24)-(tp_years*365*24);
		tp_minutes = Math.floor(tp_result/minutes)-(tp_hours*60)-(tp_days*24*60)-(tp_years*365*24*60);
		tp_seconds = Math.floor(tp_result/seconds)-(tp_minutes*60)-(tp_hours*60*60)-(tp_days*60*24*60)-(tp_years*365*24*60*60);
		singlebox=false;
		if(tp_years > 99)
			tp_years=99;
		
		if(tp_days > 99)
			singlebox=true;
		
		if(tp_years < 0)tp_years=0;
		if(tp_days < 0)tp_days=0;
		if(tp_hours < 0)tp_hours=0;
		if(tp_minutes > 60)tp_minutes=60;
		if(tp_minutes < 0)tp_minutes=0;
		if(tp_seconds < 0)tp_seconds=0;
	}
}

A very important aspect that needs to be mentioned is that these functions use global variables that were not mentioned yet. It is recommended that you add the following code with global variables at the top of the script.js file before any other code:

tp_days = 0;
tp_hours = 0;
tp_minutes = 0;
tp_seconds = 0;

Conclusion

Building a countdown timer in jQuery is not exactly a very fast and easy project as there are many aspects that need to be taken into consideration when starting. Things like what javascript classes, plugins and styles will be used, what design it will have in the front and back end, how it stores data and how it pulls it back out. Also the compatibility of all of these with other plugins or scripts and how exactly everything is calculated and what it outputs.

Let us know what you think, and if you have any additional recommendations, in the comments below!

Update: This post has been updated to amend the issues mentioned in the comments.

Update #2: Source files are now available for download at the top of this tutorial.

Original from: http://wp.tutsplus.com/tutorials/plugins/creating-an-ajax-countdown-timer-wordpress-plugin/

How to Create an Instant Image Gallery Plugin for WordPress

May 8th, 2012 Comments off

Learn how to create a simple, automatically generated image gallery plugin with thumbnail navigation for WordPress. The end result is a simple, attractive gallery with thumbnail navigation that is created automatically whenever you upload images to a post or page. No special settings, no options to configure, no hoops to jump through – it just works!


Introduction

Here is a preview of what we will be creating:


Using Instant Gallery for WordPress

Before we get into the code, let’s take a quick look at how easy this gallery is to use. For those of you who just want to grab the code and use it, this section will show you how to do that.

For those that want to learn how to create this gallery, it is still good to get a sense of how it works before we start coding. So, let’s check it out!

Instant Gallery: The 2-Minute Quick-Start Guide

1. Start with a simple, blank Post or Page in WordPress. Hit the “Upload/Insert Media” button.

2. Next, upload some images to the Post or Page. Just drag and drop your images into the box.

3. When your images finish uploading, you’ll get a list of the images and their properties. You can drag and drop the images to re-order them on this screen. Instant Gallery respects the menu order that you set up in the WordPress media browser, so re-ordering the images here will re-order them on the gallery.

4. If you want to change any properties of the image, such as the Title, Caption or Description, then you can do that just like you normally would. In its current incarnation, Instant Gallery displays the image Title in the Gallery in between the main image and the thumbnails.

Why display the Title and not the other information? As you can see from the image, WordPress automatically fills out the Title of the image (using the image’s filename) as soon as you upload it. In keeping with the theme of making Instant Gallery as fast and easy to use as possible, I wanted to use the field that WordPress fills out automatically.

5. Finally, go back to your Post or Page and enter the [instant_gallery] shortcode in the content area. Hit save, and then go view your page. That’s it!

So, that’s all there is to it. The purpose of Instant Gallery is to be the fastest, easiest way to create an image gallery by uploading images to a Post or Page in WordPress. If you think that will be useful to you, then go ahead and grab the files and have fun!

You’ll be creating beautifully simple WordPress image galleries in an instant!

Let’s take one more look at the finished product:

Now, if you are interested in learning how Instant Gallery was created, either to improve your skills as a coder, or to build upon Instant Gallery and make it better, then please keep reading!


Creating Instant Gallery

As with most WordPress projects, we’ll be using HTML, CSS, PHP, and a little bit of JavaScript to accomplish our goal.

We will proceed in the following way:

  1. HTML – Start with markup and fill it with static content
  2. WordPress / PHP – Dynamically populate our markup with content
  3. JavaScript – Apply the behavior to swap the images
  4. CSS – Complete the look and feel with CSS

Step 1 The Markup

The markup for our gallery is very simple. We just have a main containing element that encompasses the entire gallery (#instant-gallery), the primary content panel that contains our main image and its title (#ig-main), and then the thumbnail navigation area (#ig-thumbs).

	

Our navigation is an unordered list and each list item contains a thumbnail image.

For simplicity, we will just use three placeholder thumbnails in the static HTML version. In the next section we will use PHP to dynamically generate as many thumbnails as we need.

If we check out our markup now, we’ll get something that looks like this (just showing two thumbnails to keep the image size down):

So, that’s the basic markup. Not too exciting, but simple, clean HTML is the foundation of just about everything we do on the web so it’s worth taking the time to get it right.


Step 2 The WordPress and PHP

Now let’s get into the WordPress part of the tutorial. This may be the most exciting part for you Wptuts+ readers.

Let’s start by thinking conceptually about what we want to accomplish. The goal here is to have an image gallery automatically generated from any images that are uploaded to a given post or page.

In order to accomplish this, we need to know the following:

  • What post or page are we on?
  • Are there any images attached to this page? If so, let’s get them and some information about them.
  • Then, for the first image, we want to display it in the gallery, along with a caption or descriptive text.
  • Then, for all of the images (including the first) images, we want to display them as thumbnails below the gallery.
  • The first image should also be highlighted to show that it is currently selected.

With that general concept in mind, let’s take a look at the markup code from Step 1, now infused with the WordPress and PHP code we need to get the information we want. There is a fair amount going on here, so let’s break it down into smaller sections that correspond with the list above.


Step 2.1: Prepare the Query

//-------------------------------------------------
// Prepare the query
//-------------------------------------------------

	global $post;

	$args = array(
		'post_parent'    => $post->ID,			// For the current post
		'post_type'      => 'attachment',		// Get all post attachments
		'post_mime_type' => 'image',			// Only grab images
		'order'			 => 'ASC',				// List in ascending order
		'orderby'        => 'menu_order',		// List them in their menu order
		'numberposts'    => -1,					// Show all attachments
		'post_status'    => null,				// For any post status
	);

Here we are doing two main things:

First, we set up the global Post variable ($post) so we can have access to the relevant data about our post.

Second, we set up an array of arguments ($args) that define the kind of information we want to retrieve. Specifically, we need to get images that are attached to the current post. We’re also going to get all of them, and return them in the same order they appear in the WordPress gallery.

See the comments in the code snippet above to see which lines correspond to which parameters.


Step 2.2: Retrieve the Images

	// Retrieve the items that match our query; in this case, images attached to the current post.
	$attachments = get_posts($args);

		// If any images are attached to the current post, do the following:
		if ($attachments) 	

			// Initialize a counter so we can keep track of which image we are on.
			$count = 0;

			// Now we loop through all of the images that we found
			foreach ($attachments as $attachment) 

Here we are using the WordPress get_posts function to retrieve the images that match our criteria as defined in $args. We are then storing the results in a variable called $attachments.

Next, we check to see if $attachments exists. If this variable is empty (as will be the case when your post or page has no images attached to it), then no further code will execute. If $attachments does have content, then we move on to the next step.

Next, we initialize a simple counter variable so we can keep track of which image we are on. We do this because there are certain things we’ll want to output only the first time through our loop (such as the main gallery markup). It also gives us a means to assign unique IDs to each thumbnail in the navigation if we would like.

Then we open the loop that will step through each of our images.


Step 2.3: Main Galley Area

//---------------------------------------------------------
// Output the main containers and first large image;
// This is stuff we will only want to output one time.
//---------------------------------------------------------
	if($count == 0)  ?>

		
		

Here we use our counter variable to determine how many times we have been through our loop. If this is the first time, $counter will be equal to zero, and the block of code above will be executed. This code sets up the main structural elements of the gallery and populates the main image section with the first large image. This stuff only needs to happen once. For subsequent trips through the loop, $counter will be greater than zero and this block of code will be skipped.

Ok, so what’s actually going on in there? We’ve already looked at the HTML part in Step 1, so let’s focus on the PHP code that inhabits the main gallery area.

	
	 "ig-hero",
			'alt'   => trim(strip_tags( get_post_meta($attachment_id, '_wp_attachment_image_alt', true) )),
			'title' => trim(strip_tags( $attachment->post_title )),
		);
	?>

	
	ID, 'full', false, $default_attr); ?>

	
	

post_title; ?>

In the first section here, we define an array of parameters just like we did in Step 2.1. This time, however, instead of parameters for a query, we are setting parameters for a WordPress function called wp_get_attachment_image.

This function grabs the current attachment (our current image), returns the full size of the image (as opposed to a smaller size such as the Thumbnail; we’ll get into that later), and applies attributes to the image HTML tag that correspond to the arguments defined in the $default_attr array. The “alt” and “title” tags of the image are defined as you would expect, and the image is given an ID of #ig-hero so that we can easily target it with CSS.

Finally, we output image title again, this time as the Title which appears below the image. By default, WordPress sets the image Title to be equal to the filename of the uploaded image. So, when you use this technique, either (1) make sure the filenames of the images you upload are something you would like to have displayed on your slideshow, (2) edit the Title field of the images when you upload them, or (3) comment this part of the code out so that the title does not display in the slideshow at all.


Step 2.4: Thumbnail Navigation

	
	
  • "thumb selected", ); else // For all other thumbnails, just add the basic class of 'thumb' $thumb_attr = array( 'class' => "thumb", ); ?> ID, 'thumbnail', false, $thumb_attr); ?>

Now let’s take a closer look at the thumbnail navigation. At the top of this block of code we’ve repeated the opening of the #ig-thumbs list to help you orient yourself in the code. With that reference point in mind, let’s look at the actual list items themselves.

You’ll notice that we are using a little snippet of PHP to output the $count variable, plus one, to give each list item its own unique ID. This will give us just one more degree of control over the list items with CSS, should we want it. We use $count+1 so that we don’t have to start at zero.

Inside the list item, there is a conditional statement that checks one more time which iteration of the loop we are on. As we have done a few times before, we are setting an array; however, this time it is an attribute for the thumbnail images. The difference here is that we are setting slightly different parameters for the array depending on if we are on the first trip through the loop or not.

We always give the thumbnail a class of “thumb”, but on the first trip through the loop we also give the first thumbnail a class of “selected”. This is something we will target with CSS later on in order to provide a consistent user experience.

Once the $thumb_attr attributes are set, we use wp_get_attachment_image again to output the image. The main thing to note this time is that we are grabbing the thumbnail version of the image instead of the full size of the image that we grabbed above.

Then, since we are at the end of our loop, we increment our counter and begin the loop again. Once we’ve exhausted all of our image attachments, we’ll hit the end of the loop. When this happens, we close the unordered list, then the whole gallery container, and then our PHP conditional statements.


Step 2.5: Add the Shortcode

It’s great have coded up our image gallery, but it is even better if we can display our image gallery! At this point, we still don’t have any way to actually show the output on a WordPress Post or Page. We’re going to fix that right now, and fortunately this step is easy!

	//-------------------------------------------------
	// Create the Shortcode for Instant Gallery
	//-------------------------------------------------

	add_shortcode('instant_gallery', 'instant_gallery');

It feels good to have a nice quick win after the big block of code from Step 2.4. Here we’re just defining a very simple shortcode so that we will be able to add the gallery to our WordPress posts or pages.

This takes our function, called ‘instant_gallery‘ which is defined above, and creates a new shortcode with an identical name. We can then insert the gallery into our posts or pages using the shortcode [instant_gallery].

There are plenty of in-depth articles about shortcodes out there, including some good ones right here on Wptuts+. If you are new to shortcodes, here are some good starting points:


Step 2.6: Gather Our Thoughts

Whew! Ok, so that’s all the code for the gallery itself. The code we’ve written so far will retrieve a list of image attachments from the current WordPress post or page and then automatically generate a gallery according to the markup we provided. The shortcode then gives us a convenient way to insert our galleries into our posts or pages.

If we upload some awesome images of seahorses and jellyfish and then check our results, here is what we will have at this point:

From a WordPress point of view, we have done what we need to do. Without JavaScript, however, the gallery won’t actually do anything. Without CSS, it won’t look very good, either. So, let’s take a minute to digest what we’ve done so far, and then we will move on to the next step where we make our gallery come alive!


Step 3 The JavaScript

As you might expect, Instant Gallery relies on the magic of jQuery to achieve the basic level of interactivity that it requires. There are actually two parts to this. The first is loading the jQuery library into our theme correctly, and the second is the actual jQuery code which will create the behavior we need (namely, swapping images and image titles when a thumbnail is clicked).

Both of these parts offer a good opportunity to employ some insights and WordPress best practices, so if you are new to working with jQuery in the context of WordPress, pay special attention!


Step 3.1: Using Enqueue Script to Load jQuery in WordPress

As you may know, jQuery (as well as many other JavaScript libraries) come pre-loaded with WordPress. For the sake of simplicity, we will use the version of jQuery included with WordPress for this example.

This is a good opportunity to use the WordPress wp_enqueue_script function. This is the “right” way to load scripts in WordPress. It ensures that the scripts are loaded at the proper place and time as WordPress executes, and that conflicts are avoided.

The wp_enqueue_script function can be confusing, but fortunately there are plenty of good articles about it out there. Here are some useful resources about wp_enqueue_script:

	//-------------------------------------------------
	// Enqueue jQuery
	//-------------------------------------------------

	function wptuts_enqueue_jquery() 

		wp_enqueue_script('jquery');

	

	// Only add the javascript if we are NOT on the admin screen
	add_action("wp_enqueue_scripts", "wptuts_enqueue_jquery", 11);

Notice that we attach this function to the WordPress hook “wp_enqueue_scripts” which loads all the scripts that have been enqueued by “wp_enqueue_script“. Subtle difference there, but it is important!

Here is an important note about wp_enqueue_scripts from the WP Codex:

wp_enqueue_scripts hook (instead of the init hook which many articles reference), we avoid registering the alternate jQuery on admin pages, which will cause post editing (amongst other things) to break after upgrades often.


Step 3.2: Using jQuery to Bring Instant Gallery to Life

Now we can move on to the jQuery code that powers the swapping of images and titles. We only need a few lines of code to accomplish this. Some of you out there who are well versed in jQuery may even be able to suggest some more efficient ways to get the job done!

As we did with the WordPress code in Step 2, let’s walk through this conceptually before we get into the code itself. When we click on a thumbnail, we want a few things to happen:

  • First and most importantly, we want to swap out the existing image in the main hero position for another large image – the one that corresponds to the thumbnail we clicked on.
  • Second, we want to replace the title of the old image with the one that corresponds to the new image. We will do this by taking advantage of the WordPress file naming scheme. We will talk about how to do that in just a moment.
  • Third, we want to highlight the thumbnail corresponding to our large image at any given time. As we saw in Step 2.4 above, the way we designate this is with a class of ‘selected’ on the current thumbnail.
  • Finally, when a new image is chosen, we remove the class of ‘selected’ from all images, and then add it back again to the newly selected thumbnail.

So, with those key actions in mind, let’s see what this looks like in jQuery:

	//-------------------------------------------------
	// Activate Instant Gallery
	//-------------------------------------------------

	function activate_instant_gallery() 
	?>

		

	

Fortunately, the jQuery code is relatively simple, and corresponds nicely to our bullet list of required actions above.

The code is pretty well-documented, so if you don’t understand a line, the comments should help. Even so, let’s break down the jQuery, line by line (leaving aside the generic “wrapper function” of ( function ($) ) which we will discuss in a moment).

The line that begins $('#ig-thumbs').delegate is what defines the scope of our function. It is saying, whenever someone clicks on an image object (img) inside a container with an ID of #ig-thumbs, then execute the actions within the function.

The next line, which begins $('#ig-hero'), handles the actual swapping of our current image for the large image that corresponds to the thumbnail that was clicked. In this jQuery function, the thumbnail that was clicked is referred to as “this” because it was the subject of the action “click”; it is the thing that was clicked upon and triggered the function.

The method for accomplishing the image swap takes advantage of the WordPress file naming scheme. For example: When you upload an image called my-image.jpg, WordPress will create several different sizes of that image. One automatically created size will be a “Thumbnail” size which is, by default, a 150×150 square cropped out of your original image. WordPress will name this file my-image-150×150.jpg. It simply adds a “-150×150″ to the end of your filename, right before the file extension.

So, if we want to replace a thumbnail version of an image with the full-sized version of that image, then we just have to remove the “-150×150″ from the filename. This is what our jQuery is doing to swap the images.

If we wanted to replace the thumbnail with a different size of the image, but not the full sized image, we would need to know the dimensions of that other size, and then we could just switch the dimensions. For example, if we wanted to switch out my-image-150×150.jpg for a Medium sized image of 600×300, then we would just use the jQuery code to swap the “-150×150″ with a “-600×300″, and we would be left with my-image-600×300.jpg.

Next, with the line that begins $('#ig-thumbs li img'), we just remove the CSS class of “selected” from all of the thumbnails, and then the line below that adds the class of “selected” to “this”; that is, the image that was clicked.

Finally, with the line that begins $('#ig-title'), we switch the Title of the old image with that of the new image. This line takes the contents of a containing element with an ID of #ig-title

Step 3.3: Using jQuery in the Context of WordPress

Now, since we are performing all of these operations within the context of WordPress, we should be aware of an important detail about how WordPress loads jQuery.

WordPress runs jQuery in “no conflict mode” so as to avoid conflicts with other JavaScript libraries. In practical terms this means that the useful $ shortcut commonly used in jQuery won’t work in WordPress by default.

Fortunately, this topic has been discussed at length already. If you are interested in learning more about the reasons for this, Chris Coyier has a great article on Digging Into WordPress that addresses precisely this issue. For the purposes of this article, we just need to wrap our jQuery function in a generic function to re-enable use of the $ shortcut within our code snippet.

Finally we add this code using a built in WordPress hook – wp_footer – to load the script correctly and only after the rest of the page has loaded.

With the jQuery in place, let’s take a look at what we have so far. Now our gallery is interactive, and clicking on one of the thumbnails correctly replaces the main image and corresponding title. In the example image below, you can see that we’ve clicked on the second thumbnail and both the main image and its title have been replaced as we would expect.

So, it works, but it still doesn’t look very good. Fortunately, we can tidy things up with some basic CSS. And that’s just what we’ll do in the next step.


Step 4 The CSS

Step 4.1: CSS for Instant Gallery

Now it is finally time to style our creation and make it look more like an actual image gallery. Since the major focus of this tutorial was on the WordPress and jQuery functionality, I’ve kept the CSS for this gallery extremely simple. Here is the CSS code for the gallery:

	/* Instant Gallery */

	#instant-gallery 
		overflow: hidden;
		display: block;
		width: 100%;
		margin-bottom: 1.5em;
	

	/* Main Display Area */

	#ig-main 
		width: 100%;
	

	#ig-hero 
	

	#ig-title 
		margin-top: 1.5em;
		margin-bottom: 1.5em;
		line-height: 1.5em;
	

	/* Thumbnails */

	#ig-thumbs 
		overflow: hidden;
		margin: 0;
	

	#ig-thumbs li 
		margin-right: 1.5em;
		margin-bottom: 1.5em;
		float: left;
		display: block;
		cursor: pointer;
	

	#ig-thumbs img 
		width: 75px;				/* Customize to change Thumbnail Width */
		height: 75px;				/* Customize to change Thumbnail Height */
		padding: 1px;
		border: 1px solid #ddd;
	

	#ig-thumbs li img:hover,
	#ig-thumbs li img.selected 
		border: 1px solid #aaa !important;
	

There is nothing too complicated about our CSS. Just the basic selectors and styles necessary to create the gallery. If you want to modify the CSS to make your gallery a bit more fancy, I have provided all of the selectors you would need to do so.

One thing to notice here is that I’ve constrained the size of the thumbnails to 75×75 instead of the 150×150 size at which we retrieved them from WordPress. The 150×150 size is a little too large for my tastes; I like the smaller thumbnails so you can fit more under the gallery. If you want to use a different size, all you have to do is change the width and height of the thumbnail images on the two lines marked on the CSS.


Step 4.2: Using Enqueue Style to Load CSS in WordPress

Perhaps more interesting than the CSS itself is the manner that we use to load it. We could just do a simple link tag and hook it into our header using the wp_head hook, but there is a better way.

Taking a hint from the enqueue_script function that we used to load jQuery, we can use a similar function, wp_enqueue_style, to load our style sheet. As with enqueue_script, this is the preferred way to load stylesheets within WordPress. It is good to practice these techniques even with simple projects such as this because it allows you to focus on understanding the technique and why it works without worrying about debugging massive amounts of code. There is a certain satisfaction in doing something simple very well!

	//----------------------------------------------------------------------
	// Import Stylesheet
	//----------------------------------------------------------------------

	function add_stylesheets() 

		// change this path to load your own custom stylesheet
		$css_path = WP_PLUGIN_URL . '/instant-gallery/instant-gallery.css';

		// registers your stylesheet
		wp_register_style( 'instantGalleryStyles', $css_path );

		// loads your stylesheet
		wp_enqueue_style( 'instantGalleryStyles' );
	

	// Only add the stylesheet if we are NOT on the admin screen
	if (!is_admin()) add_action( 'wp_enqueue_scripts', 'add_stylesheets' );

So that is how you use wp_enqueue_style. Very similar to enqueue_script. You’ll notice that there is another command in here as well: wp_register_style. This function simply registers a CSS file with WordPress for later use with wp_enqueue_style.

Now our image gallery finally looks as good as it functions!


All Together Now

Check out the finished product:

It looks very simple, and that’s exactly what we want. The point of this gallery is to be the simplest, fastest way to automatically generate an image gallery from images uploaded to a WordPress post of page, nothing more!

Please feel free to check out a live demo of Instant Gallery for WordPress on my personal website.

The completed code is too long to display here in full, so please feel free to download the source files (at the top of the article) and have a look at everything on your own.


Conclusion

We have just created an instant image gallery with thumbnail navigation for a WordPress!

Throughout this tutorial I’ve done my best to incorporate good practices on everything from clear markup, semantic CSS, and even the way stylesheets and javascript are loaded. If you played along and worked through the steps, then I hope you learned a new technique or two. If you are just here for the finished code, I hope you find it useful and that you can use it confidently and with the knowledge that you are using some simple code that was made with love.

As with all coding projects, there are always ways to make improvements. If you can think of any way to make this code better or more robust, I welcome any and all constructive feedback in the comments!

I also welcome any and all suggestions on how to improve the plugin and make it more powerful or elegant. I am not very interested, however, in making it more complicated or adding a bunch of features. There are lots of full featured image galleries out there already, and I would like this one to remain simple and fulfil one very specific purpose.

Finally, I would like to thank Japh Thomson for giving me the opportunity to write for Wptuts+, and thank Envato for building a great educational community on the web. Most importantly, thank you for reading!

I look forward to your feedback, please let me know in the comments if you use Instant Gallery on any of your websites!

Original from: http://wp.tutsplus.com/tutorials/plugins/how-to-create-an-instant-image-gallery-plugin-for-wordpress/

CSS3 Menu and Navigation Tutorials

April 19th, 2012 Comments off

All of the CSS3 navigation tutorials we have for you today are all fully functional and could easily be used on a live site. But we do prefer to think of them all as being more experimental and proof-of-concept rather than being a robust end-product (a sprinkle of jQuery always makes everything better!). What they do offer is an opportunity to roll-up your sleeves and delve into some ground-breaking code.

Anyway, here they all are:

Creative CSS3 Animated Menus

Creative CSS3 Animated Menus

The idea of this tutorial is to have a simple composition of elements, an icon, a main title and a secondary title, that will be animated on hover using CSS transitions and animations.
Creative CSS3 Animated MenusDemo

CSS3 Animated Dropdown Menu

CSS3 animated dropdown menu

With this tutorial you will learn how to build this awesome CSS3 animated dropdown menu with some pretty cool features. A little bit of jQuery is used for IE.
CSS3 Animated Dropdown MenuDemo

Creating a Cool CSS3 Dropdown Menu

Creating a cool CSS3 Dropdown Menu

With this tutorial you will be shown how to create a multilevel CSS3 dropdown menu that will render perfectly with Firefox, Chrome and Safari. The menu does work in IE8+, but the rounded corners and shadows will not be render.
Creating a cool CSS3 Dropdown MenuDemo

CSS3 Minimalistic Navigation Menu

CSS3 Minimalistic Navigation Menu

In this tutorial you will learn how to build a simple CSS3 animated navigation menu, which degrades gracefully in older browsers and is future-proofed to work with the next generation of browsers.
CSS3 Minimalistic Navigation MenuDemo

CSS3 Animated Menu

Making a CSS3 Animated Menu

Using the power of CSS3 effects and transitions, with this tutorial, you will learn how to to build a navigation menu with some neat features such as the :target pseudo selector and :after elements.
CSS3 Animated MenuDemo

CSS3 LavaLamp Menu

How to Create a CSS3 Wheel Menu

Pure CSS3 LavaLamp MenuDemo

CSS3 Multi-Level Drop-Down Menu

Pure CSS3 Multi Level Drop Down Navigation Menu

In this tutorial you will learn how to create a pure CSS3 Multi Level Drop Down Navigation Menu. This navigation menu renders perfectly on Firefox, Chrome and also Safari.
CSS3 Multi-Level Drop-Down MenuDemo

Responsive Content Navigator with CSS3

In this tutorial you’ll be shown how to create a responsive content navigator with CSS only. The idea is to have several slides or content layers that will show or hide using the :target pseudo-class. With CSS transitions you can make the slides appear in a fancy way.
Responsive Content Navigator with CSS3Demo

Accordion with CSS3

With this tutorial, using hidden inputs and labels, you will learn how to create an accordion that will animate the content areas on opening and closing.
Accordion with CSS3Demo

Sweet Tabbed Navigation

Sweet Tabbed Navigation

Here you will learn how to create a sweet tabbed navigation using CSS3.
Sweet Tabbed NavigationDemo

Circle Navigation Effect with CSS3

Circle Navigation Effect with CSS3

In this tutorial you will be shown how to create a beautiful hover effect for an image navigation using only CSS3.
Circle Navigation Effect with CSS3Demo

Apple.com Menu Using Only CSS3

The Apple.com navigation menu created using only CSS3

In this tutorial you will learn how to create the Apple.com navigation menu using only CSS3.
Apple.com MenuDemo

Stylish Menu with CSS3 Transitions

Create a Stylish Menu with CSS3 Transitions

In this tutorial you will learn how to create a stylish menu that features some cool rollover effects using CSS3 transitions.
Stylish Menu with CSS3 TransitionsDemo

Slide Effect Menu

Slide effect menu with the Apple-Style

In this tutorial you will learn how to create Slide effect menu with the Apple-Style.
Slide Effect MenuDemo

CSS3 Dropdown Menu

CSS3 Dropdown Menu

In this tutorial you will learn how to create an outstanding Dropdown Menu using CSS3.
CSS3 Dropdown MenuDemo

Sliding Navigation without JavaScript

Sliding Navigation without JavaScript

With this tutorial you will learn how to create Sliding Navigation without JavaScript.
Sliding Navigation without JavaScriptDemo

Sweet CSS3 Vertical Navigation

Sweet CSS3 Vertical Navigation

In this tutorial you’ll learn to create a vertical CSS3 navigation, without the use of images. The menu will display a circle with an icon in the center and when the user hovers over the circle, it will expand and show a short description.
Sweet CSS3 Vertical NavigationDemo

CSS3 Vertical Multicolor 3D Menu

CSS3 vertical multicolor 3D menu

CSS3 Vertical Multicolor 3D MenuDemo

jQuery Style Menu with only CSS3

jQuery style menu with CSS3

jQuery Style Menu with only CSS3Demo

CSS3 Multicolor Menu

CSS3 multicolor menu

In this tutorial you’ll create a nice multicolor and cross-browser sliding (using transitions) CSS3 menu.
CSS3 Multicolor MenuDemo

CSS3 Mega Drop-Down Menu

CSS3 Mega Drop-Down Menu

In this tutorial, you’ll learn how to build a cross-browser, CSS-only drop-down mega menu, using CSS3 features.
CSS3 Mega Drop-Down MenuDemo

Slick Menu using CSS3

Slick Menu using CSS3

Slick Menu using CSS3Demo

Dark Two Level Menu

DARK MENU: PURE CSS3 TWO LEVEL MENU

Dark Two Level MenuDemo

Creating CSS3 Dropdown Menu

Creating CSS3 Dropdown Menu

In this detailed tutorial you will learn how to create the above CSS3 Dropdown Menu.
Creating CSS3 Dropdown MenuDemo

Sexy CSS3 Menu

Sexy CSS3 menu

In this tutorial, you will learn how to create a good looking menu using some CSS3 magic.
Sexy CSS3 MenuDemo

CSS3 Dropdown Menu

CSS3 dropdown menu

CSS3 Dropdown MenuDemo

Cool CSS3 Navigation Menu

Cool CSS3 navigation menu

Cool CSS3 Navigation MenuDemo

Click Action Multi-level CSS3 Dropdown Menu

Click action Multi-level CSS3 Dropdown Menu

Click Action Multi-level CSS3 Dropdown MenuDemo

Accordian like CSS3 Onclick Vertical Navigation

Creating an Accordian like CSS3 Onclick Vertical Navigation

Accordian like CSS3 Onclick Vertical NavigationDemo

CSS3 Hover Tabs without JavaScript

CSS3 Hover Tabs without JavaScript

CSS3 Hover Tabs without JavaScriptDemo

Creating a CSS3 Dropdown Menu

Creating a CSS3 Dropdown Menu

Creating a CSS3 Dropdown MenuDemo

CSS3 Wheel Menu

How to Create a CSS3 Wheel Menu

CSS3 Wheel MenuDemo

You might also like…

CSS3 Compatibility Tools, Resources and References for Internet Explorer →
CSS Form Templates, Tools & Services →
25 Free Fonts Perfect for @fontface → & @fontface Icons →
Liquid, Fluid and Elastic Layout Templates, Tools and Frameworks →
Pure CSS Alternatives to Javascript →
40 Essential CSS Templates, Resources and Downloads →

Or, you could browse our extensive CSS Archives →



Original from: http://feedproxy.google.com/~r/speckboy-design-magazine/~3/6f1QFpUxyz4/

Categories: Web development Tags: ,

Captivate your Audience with Typography

March 12th, 2012 Comments off

Modern web designers are incorporating innovative new concepts for digital type. In the previous decade we have witnessed the Internet transform into a powerful tool for sharing media all around the world. More specifically digital designers have adapted and web trends continue to change over time.

Austin Eastciders drink

Text on a page will always be the most uniform way of communication. It’s up to web designers to mold this text in a tasteful and easy-to-read manner. In this guide I’ll share a few tips for captivating your visitors with brilliant online typography. It only takes a bit of time and patience to understand these techniques and apply them into your own layouts.

Design for Practicality

Creating text on paper is a much more dynamic task than building for the web. You are often limited with space and molding text around a set page dimension. Some of these concepts will carry over in web typography, but your average page layout is much more clean-cut.

You don’t want to extend your ideas outside the box so far that it scares away your visitors. Stick with what works and what looks practical. Typically you would plan out styles for your paragraphs, inline quote blocks, a couple different headings, and anchor links. If you have the need for other text elements(such as unordered lists) you should match up their styles with headings and paragraphs as well.

Most commonly your pages will consist of paragraph text broken up into sub-headings. Articles will often sprinkle links, italics, and bold formatting to keep the reader’s attention. Your images may also look nicer with a small caption area. As long as the page outline can be easily skimmed you are in good shape.

Custom Font Faces

The new CSS3 property @font-face allows designers to incorporate their own custom fonts. This has long been a dream of mine thinking back to the days of working to kill bugs exclusively in Internet Explorer 6.

Working with the same set of “standard” fonts can grow weary and a tad boring. Designers need to feel confident in sprucing up their webpage type with new font families. We have briefly explained advancing web font techniques and how you can use .ttf or .otf files on your own. This solution works perfectly in supported web browsers, but there is another 3rd party option.

Google Web fonts selector

The ever popular Google Web Fonts has been growing in size with up to about 500 unique families to choose from. With any Google account you have access to this free directory of web fonts. And best of all you can select multiple choices from the interface and Google will output all the code you need to include in your page.

TypeKit typography online web design

Typekit is another option powered by Adobe. Although unlike Google free users would be limited to a trial library of fonts. You can check out their full list with just over 700 unique typefaces. This plan would cost $50/year which may not be a practical solution to everyone. If you only need one or two unique font choices then I recommend going through Google or hosting them yourself with CSS3 queries.

Experiment with Ideas

Luckily it’s a lot easier to play around in CSS code than other means of development. There are so many unknown properties you can utilize and implement on your typography. Don’t be afraid to step out of your comfort zone and mess around with some unique styles. Change up background colors and rounded corner effects.

Even if your ideas don’t work out you’ll have a better sense of what looks good and what doesn’t. Spend time going over your color scheme options so you can match paragraphs, headers, and link styles together. You want to build contrast between the text color and page background. Additionally check out some of my example CSS properties in the list below:

  • font-variant
  • letter-spacing
  • word-spacing
  • text-indent
  • line-height
  • text-transform
  • vertical-align
  • text-shadow

Using Big Examples

If you have enough room in your layout I recommend keeping your headers big. As in, super oversized big for

tags. These will be the most important typographic elements on the page and you want them to stand out.

Get Finch - new web design eulogy

Big jumbo-sized text is a trend often written about and seen in newer design models. It’s a great technique which will absolutely capture attention. But then you need to adequately match up the rest of your page text sizes. Paragraph texts shouldn’t be too small or else your headers will overshadow them.

I actually recommend keeping all paragraph text around 14px-16px or more. Gone are the days where 11px Arial will still look “professional”. It may fit nicely into your layout mold but serves very little practical purpose. Nobody wants to struggle reading smaller texts anyways – but it can be useful as a secondary style class. Smaller texts are great for labels, captions, or quick notes within your main content.

Writing Flow

As important as your individual CSS styles is the idea of your overall page layout design. Your text and paragraphs should flow easily and not feel constrained into the page. Try to keep your ideas brief and summarized to a point.

New MacBook for work

Your average Internet user does not hold such a large attention span. And this goes double for long pages of text. If you have content broken down into many smaller paragraphs it appears much less daunting of a task to read through. Also try adjusting your line-height and paragraph margins to add some extra white space padding. This goes a long way to increasing the readability of your text.

Design Showcase

Along with these ideas I’ve put together a small gallery of truly captivating web typography. These examples should provide a bit of inspiration when brainstorming for your own layouts. If you have additional suggestions feel free to share with us in the post discussion area.

Delta Tango Bravo

Delta Tango Bravo

Viljami Salminen

Viljami Salminen

SimpleBits

SimpleBits design blog

CaptainDash

CaptainDash home page

Yes! Nurse

Yes! Nurse design

24 ways

24 ways org blog

Zee Design

Zee consulting

polargold

polargold

hellobar web toolbar

hello bar web toolbar

i love typography

i love typography

Goodness

Goodness web design

255 Creative

255 Creative

Web Designer Wall

Web Designer Wall

Concentric Studio

Concentric Studio

Hot Meteor

Hot Meteor

Life in Greenville

Life in Greenville

Astheria

Astheria

Winnie Lim

Winnie Lim design portfolio

Fever App

Feed a Fever

InfinVision

InfinVision

You might also like…

25 Completely Free Fonts Perfect for @fontface →
20 @fontface Icon Sets →
50 Examples of Effective Uses of Typography Within Web Design →
CSS Form Templates, Tools & Services →
Liquid, Fluid and Elastic Layout Templates, Tools and Frameworks →
Pure CSS Alternatives to Javascript →
40 Essential CSS Templates, Resources and Downloads →



Original from: http://feedproxy.google.com/~r/speckboy-design-magazine/~3/u6HHAgHa-iU/

Website Speed Part 4 : PHP Programming for Speed

March 12th, 2012 Comments off

Programming for speed is not what most coders think of. What they tend to consider first, and usually only, is getting it working. Sometimes people will talk of refactoring to reduce the amount of code, but again this is usually only for those that suffer with the luxury of having too much money and time.

I wish I had that luxury, to be able to spend twice as long on a problem to make a perfect solution. In truth I don’t most of the time, as I am out there getting new clients, making other products or not in the fortunate position to have a client with very deep pockets.

To counteract these things I have a bunch of methods stored in my head that allow me to choose the best path first time (I hope!). I am going to share these best practices with you so you can maybe do the same, maybe even better. If you have any great speed suggestions for coding, please comment and I will append it to this post.

Also, please note that this is not an exhaustive list. This is more of a pointer to things you should consider in your favorite coding language. Although this is for PHP specifically, I’ve tried to keep it as generic as possible to make it possible for all coders, no matter the language, to benefit.

Making IF ELSE smaller

IF is possibly the most used statement from all the programming languages, and I think the most used by a noob programmer (hey I was one once, I remember my code).

Common IF ELSE usage

          if ( $something == true )
              $value = 'yes';
          else
              $value = 'no';
          

Now using only IF

          $value = 'no';
          if ( $something == true )
              $value = 'yes';
          

As you can see all that has been done is that value is pre-set to ‘no’ and only gets changed to ‘yes’ if something is true. Both bits of code have the same outcome, one has less code.

If you only have 1 command inside the if statement then you can take things a little further. PHP does not require that you have the curly brackets when there is just one line.

          $value = 'no';
          if ( $something == true )
              $value = 'yes';

Ternary operators

We can go a stage further and have Ternary Operators. These are mathematical instructions that allow for a yes/no answer, just like IF.

IF presented as ternary operation

          $value = ( $something == true ) ? "yes" : "no" ;

Again the same IF ELSE statement, made much smaller. What it does is check the if the statement inside the brackets is either true or false, if it is true it will set value to be “yes”, if it is false it will set value to be “no”

syntax of ternary operators

          output = ( true/false condition ) ? true-value : false-value ;

It is not essential to have an output, as the true or false value could call a function and not return a value.

Using Range to create an array of numbers

Often people will code an array with just a bunch of numbers in it so that they can loop through it.

PHP code to create a select drop down list

          // selected item value
          $item = 12;
          // create array of numbers
          $array_of_numbers = array( 2,4,6,8,10,12,14,16 );
          // start the select
          echo "";

Now the same thing shorter with range

          // selected item value
          $item = 12;
          // start the select
          echo "";

Range is a really handy thing, as what it does is created an array of numbers (integers). It has the following syntax in php:

          range($start_number, $end_number, $increment);

The only needed compulsory items are the start and end number, the increment defaults to 1, but can be any number you like.

A range function is available in most languages but is unfortunately not available in Javascript out of the box, so to make this same saving in code you would be best to use a FOR loop

FOR loop version

          // selected item value
          $item = 12;
          // start the select
          echo "";

Turbo charging the FOR loop

Many people like to use a for loop as they believe that it is faster than a foreach. While this is often true, it does not offer the flexibility of foreach and with the wrong programming techniques can be slower

The slower FOR loop

            // some text as a string
            $text="We love SpeckyBoy";
            // loop through all the characters
            for($i=0; $i < strlen($text); $i++)
                // look for the o in the text string at the position of $i using a ternary operator
                // echo true or false value as needed
                echo ( substr($text,$i,1) == 'o' ) ? "its an o" : "no o here";
            

The faster FOR loop

            // some text as a string
            $text="We love SpeckyBoy";
            // get the length of the string
            $length = strlen($text);
            // loop through all the characters
            for($i=0; $i < $length ; $i++)
                // look for the o in the text string at the position of $i using a ternary operator
                // echo true or false value as needed
                echo ( substr($text,$i,1) == 'o' ) ? "its an o" : "no o here";
            

The 2nd for loop is faster as it does not need to re-check the string length each time the loop runs. The first loop will check the string length 17 times with the text used

Making your code easier to maintain, and faster

I often see the same problem with my noob code when I re-visit it. The code is all written on 1 line and very long. Check this bit of code as an example:

          $html = "";
          echo $html;

It works just fine, and will be ok for any implementation, but there are some problems with it. For example if the class is empty, it is wasteful to code the empty class setting. While this may not make so much difference to a Javascript implementation, as this is being generated on the server with PHP, you’d be sending extra bytes to the clients browser which are not required. This of course will make the most difference when making AJAX calls and waiting for the reply, where extra bytes can make much more of an impact.

An easier way to maintain

          $attributes = " name='" . $name  . "' ";
          $attributes .= " id='" . $id  . "' ";
          $attributes .= " value='" . $value  . "' ";
          $attributes .= ($theclass != '' )?  " class='" . $theclass  . "' " : "" ;
          $attributes .= ($selected == $value )?  " checked " : "" ;
          $html = "";
          echo $html;

As you can see, much easier to read, much easier to maintain, and used on the server side will produce less HTML code.

Don’t echo every line only the final output

It’s much easier to echo every line, or pass control back to HTML, than it is to write every line to a variable, yet writing the output to a variable first and only echoing at the end is the faster way to process

The easy way to do things, with a few variations

    echo "

" . $title . "

"; ?>

The more server friendly way to do things

    $output = "

" . $title . "

"; $output .= "" . date() . ""; echo $output;

OK, this is a very simplistic example of what you should do as it is only 2 lines and then output.

Rounding up

This is a very short list of things to help make your PHP coding faster and easier to maintain. There is of course many more things that you can do to reduce the amount of code that you do use, or the speed that it runs at.

Most of these techniques can be taken across to other programming languages, so when your coding in Javascript or .NET give it some thought and you will be making things much faster.

More from the Website Speed series…

Website Speed Part 1: Write More Efficient CSS →
Website Speed Part 2: Working With and Optimizing Images for the Web →
Website Speed Part 3 – Caching WordPress →



Original from: http://feedproxy.google.com/~r/speckboy-design-magazine/~3/CTFFkSg11qw/

Say Hi To Anchor – A Super-Tiny CMS

March 9th, 2012 Comments off

I’m going to make a bold assumption here, but I bet you’ve got a blog. If you do, then you join a crowd of millions, all penning their deepest thoughts and documenting their life. It really is hard to stand out from the crowd though.

Anchor aims to fix that. Based on the technology behind my blog, Anchor’s a super-tiny content management system, built especially in mind for art-directed posts; that is, a blog where every article is designed (and coded) differently. If you’ve ever used WordPress before, you’ll know how to use Anchor; if not, it doesn’t matter. You’ll still know.

So, why design custom?

It’s a good question; although it does take a bit more effort and planning than a normal blog, it pays off a lot more, it showcases your design talent, and it really makes you think about blogging at a core level. It’s great fun, trust me.

But I don’t want to/can’t design custom posts. Can I still use Anchor?

Anchor, although built for custom posts, it’s perfectly capable for a standard blog. The only difference is that you don’t add your custom CSS/Javascript. The screenshot below is of the default administration interface you’ll see when using Anchor. It’s simple, beautiful, and easy to use. There’s no excess clutter; everything has been professionally-designed for the best user experience, so you, your clients, or anyone can use it.

Why should I use it instead of WordPress?

As of version 0.6, Anchor is incredibly lightweight: at 170kb, it’s far smaller than WordPress (and most content management systems out there); it’s faster, outperforming WordPress, Joomla, Drupal, and various other CMSs in both page load times and database query optimisation; it’s beautiful (although I might be a bit biased here), and we’ve got a great community.

Of course, if you’re working on larger, non-blog sites, WordPress is probably best. Anchor focuses on a blog, and aims to do it well.

What makes it different?

If there was one thing I liked most about Anchor, it’d be theming. Anchor has one of the best theming engines out there; it’s both simple and powerful. Using a simple PHP5.3+ function-based system, you can truly customise your blog to perfection. Of course, that’s not all; apart from its custom post design, Anchor has a few unique features built-in that really help your blog stand out. Here’s a couple of my favourite ones:

  • Custom Fields: Similar to WordPress’ custom fields, Anchor allows you to attach custom key/value pairs of data to any post. This is incredibly useful, as it lets you have an infinite amount of content.
  • Custom Functions: If you’re happy with writing PHP, Anchor provides you with two functions, bind and receive, which allow you to write custom functionality for every page on your site (e.g a custom contact form, fetching Dribbble shots, or a Twitter feed – the sky’s the limit!).
  • Status Check: If something’s wrong with your blog, you’ll be the first to know; it’s a box in the sidebar that notifies you of any problems, security holes, or anything you’ll need to be aware of.
  • High-Quality Themes: Anchor prides itself on the highest level of quality in its designs, and the themes are no exception. Every theme built for Anchor has been carefully built to both look and work stunningly. Check out the Theme Garden for some examples of what’s been done.

Installing and using Anchor

WordPress has its famous five-minute install; Anchor has its not-so-famous five-second install. Provided you’ve got PHP 5.3 or greater, and access to a MySQL database, you’ll have Anchor up and running within a flash. Just download it, follow the simple installer, and keep a note of your login details (you can change them later, though).

Once it’s installed, you’re free to use and abuse Anchor; it’s licensed under the WTFPL, which allows you to do whatever you want (just be nice); you’re allowed and encouraged to use Anchor for both personal, commercial, and any other reason you can think of.

That’s it!

Hopefully I’ve persuaded you to use Anchor; if I have, great! I wish you the best on your adventures with Anchor, and if you ever get stuck, you can contact the Anchor team on Twitter, or in the official forums. If not, I’m sorry. Maybe this will help?



Original from: http://feedproxy.google.com/~r/speckboy-design-magazine/~3/O4-wvrXEq_A/