Archive

Posts Tagged ‘tutorials’

Design Patterns in WordPress: The Singleton Pattern

May 14th, 2013 Comments off

This entry is part 2 of 2 in the series Design Patterns in WordPress

Throughout this series, we’re taking a look at the significance of design patterns and the roles that they play in WordPress development.

In the first post in the series, we took a high-level survey and even reviewed the Observer Pattern to see how it’s possible to register various functions or objects with certain events that occur within the lifecycle of an application.

In this post, where’s going to take a look at the Singleton Pattern.

Specifically, we’re going to take a look at the definition of the pattern and how it works, we’re going to review a diagram of what the architecture of the pattern looks like, we’ll cover some sample code for the pattern, and then we’ll discuss the advantages of the pattern as it relates to WordPress development.

/>

The Singleton Pattern

Wikipedia defines the Singleton Pattern as follows:

In software engineering, the singleton pattern is a design pattern that restricts the instantiation of a class to one object.

Perhaps a simpler way of explaining the pattern is this: The Singleton Pattern ensures that a class can only have one instance and it provides a single way to retrieve an instance of itself.

So Why Does This Matter in WordPress?

As far as theme development is concerned, I personally don’t see much of a use for it unless you’re bundling some type of helper class or library with your theme; however, if you’re building plugins, then this can be exceptionally useful.

As of now, there are really only a handful of ways to instantiate plugins (excluding widgets – that’s another topic) within WordPress:

  • You can instantiate the plugin at the bottom of your plugin file, but this can lead to an orphaned object
  • You can stick the plugin in the PHP $GLOBALS collection, but this can be dangerous as you could trash something that already exists or it’s making the collection needlessly larger
  • If you instantiate it with, say, each page load then the data isn’t being persisted unless you serialize and hammer the database each time the plugin is instantiated

None of the above are particularly good strategies (although you could make a case that they all work).

However, we care more than just getting something to work, right? We want it to work and we want an elegant solution to the problem. This is where design patterns – more specifically, the Singleton Pattern – come into play.

/>

What It Looks Like

First, let’s take a look at a diagram of the Singleton Pattern. Check out the diagram below, then we’ll talk about the specifics after the image:

The Singleton Pattern

So here are the key features of the Singleton Pattern:

  • There is a private, static instance variable defined in the attributes that is used to maintain a reference to the class
  • The constructor has been marked as private
  • There is a public static function named get_instance which is used to return an instance of the class

Nothing too complicated, but I think reviewing the code for the Singleton Pattern goes a long way in making it a bit clearer, so let’s do that now:

class Foo 

	/*--------------------------------------------*
	 * Attributes
	 *--------------------------------------------*/

	/** Refers to a single instance of this class. */
	private static $instance = null;

	/*--------------------------------------------*
	 * Constructor
	 *--------------------------------------------*/

	/**
	 * Creates or returns an instance of this class.
	 *
	 * @return	Foo	A single instance of this class.
	 */
	public function get_instance() 

		if ( null == self::$instance ) 
			self::$instance = new self;
		

		return self::$instance;

	} // end get_instance;

	/**
	 * Initializes the plugin by setting localization, filters, and administration functions.
	 */
	private function __construct() 

	 // end constructor

	/*--------------------------------------------*
	 * Functions
	 *--------------------------------------------*/

} // end class

Foo::get_instance();

Obviously, there’s been a lot of code left out of the above class, but the pattern’s principles remain.

Notice that we have a private, static instance variable that’s used to refer to this class. Specifically, it’s set in the get_instance function whereas the constructor has been marked as private.

Typically, when instantiating classes, the constructor is the function that is called whenever we initialize classes; however, in this case, the constructor is marked as private.

So what gives?

Notice that we have a public get_instance function just above the constructor. This function literally checks to see if the static instance variable is null and, if so, creates a new instance of the class (which it can do since it’s within the context of the class); otherwise, it returns the current instance.

This is how no more than a single instance of a class is created.

Finally, note that we instantiate the class not with the standard new keyword, but by calling get_instance. Not only that, but we also get future references to the class by using the same method.

So, for example, let’s say that you’re working in another template and you need to call a function – say bar() – that exists in your plugin. In that case, you’d do something like this:

$foo = Foo::get_instance();
$foo->bar();

Pretty neat, isn’t it?

/>

The Advantages of the Singleton Pattern

Despite the fact that we’ve covered the Singleton Pattern from an architectural and a practical standpoint, we haven’t actually talked about the advantages of the pattern.

Generally speaking:

  • The Singleton Pattern prevents other objects or clients from duplicating instances of the class. This makes sure that there’s only one copy of the data maintained at any given time. All access to the object is done so by the single instance.
  • We have a wide array of flexibility when it comes to implementation because we can actually impact the instantiation process (though this is a bit out of scope for this particular post).

Perhaps the largest drawback from using the pattern is lack of clarity that the plugin actually uses the pattern. If someone tries to instantiate the class, instantiation will fail because there’s no public constructor.

As such, documentation is key.

/>

Conclusion

Whether you’ve seen them before or this is your first foray into design patterns, the Singleton Pattern is arguably the simplest design pattern there is. It’s easy to implement, and it provides a significant source of functionality when implemented correctly especially as it relates to web applications.

In the next post, we’ll take a look at another pattern – the Simple Factory Pattern – which is useful when you have a number of classes each of which has a unique purpose and that will be needed based on certain input criteria.

Original from: http://feedproxy.google.com/~r/Wptuts/~3/LiE2W9rPjEo/

Design Patterns in WordPress: An Introduction

May 10th, 2013 Comments off

This entry is part 1 of 2 in the series Design Patterns in WordPress

For those who have an extensive background in software engineering, design patterns should be familiar territory; however, there’s an entire group of developers – especially in the web development community – who aren’t necessarily familiar with design patterns (even though they’ve likely used them!).

In this series, we’re going to take a look at design patterns, specifically in the context of WordPress, how they’re useful, and some practical examples that we can use in our themes and plugins.

The ultimate goal of the series is to provide a solid definition of what design patterns are, why they’re useful, how they’re used in WordPress core, and then review two popular examples that we can easily employ in our own work.

Before we get to taking a look at some practical examples, let’s define design patterns, and look at an example of how they are used in WordPress core.

/>

Design Patterns Defined

For those of you who have never heard of or who have never used design patterns, it’s important to understand what they are before we actually begin using them in our work.

Wikipedia provides the following definition:

A design pattern in architecture and computer science is a formal way of documenting a solution to a design problem in a particular field of expertise. An organized collection of design patterns that relate to a particular field is called a pattern language.

Perhaps a more simplified definition would be:

A pattern is a design that can be applied to a problem in a specific situation.

If that’s still not clear, think of it this way:

  • Whenever you’re building a piece of software, you’re likely to recognize that you’re solving a problem that you’ve already solved before. As such, you know how to solve it.
  • Naturally, the solution to the problem will be a slightly more generalized form that’s applicable to how you’ve previously applied it.
  • This generalized form of the solution can be considered the design pattern.

The general implementation and architecture will look exactly the same; however, the specifics of the implementation will naturally vary from project-to-project, but that’s simply the nature of the beast.

In the upcoming sections and upcoming articles, we’ll be taking a look at this in a bit more detail.

/>

Design Patterns in WordPress

If you’ve done any type of WordPress development involving the hook system – that is, you’ve written entire plugins, themes, or even a simple function and taken advantage of the add_action or add_filter functions – then you’ve used design patterns.

WordPress uses what’s called an event-driven design pattern. There are several variations of event-driven design patterns one of which we’ll review momentarily, but the gist of the patterns are all the same:

  • Part of the pattern implements what’s known as a publisher
  • Part of the pattern implements what’s known as a subscriber

Generally speaking, the publisher broadcasts a message that something has happened to all objects that are subscribed to that particular publisher.

Another way of looking at this is that, in software, whenever something happens we say that an event is raised. Perhaps the most common place we see this in web development is in JavaScript with things such as the mouse being clicked, a key on the keyboard being pressed, or something similar.

We then write functions that handle those functions, and these functions are appropriately referred to as event handlers because they are responsible for handling the case when an event happens.

Not terribly complicated, right? Honestly, sometimes I think the terminology can be more confusing than the actual implementation.

So anyway, in the context of WordPress – or any web application, for that matter – events aren’t limited to key presses or mouse clicks. Instead, it can happen during various parts of the page load lifecycle, when data is written to the database, when data is read to the database, and so on.

Ultimately, you can implement the pattern however you like so that you can provide hooks into which developers can register functions to fire as soon the event occurs.

This brings us full circle back to WordPress’ architecture: Hooks are placed throughout the code such that we’re able to register a function to fire whenever something occurs (that is, whenever an event happens).

/>

A Look at an Event-Driven Architecture: The Observer Pattern

There are a number of event-driven design patterns, one of which is known as the Observer Pattern. This particular pattern is also known as the Publisher-Subscriber Pattern or, more concisely, Pub-Sub.

In the simplest implementation of this pattern, there is a single publisher that is responsible for broadcasting messages to one or many subscribers. The subscribers are responsible for registering themselves with the publisher, and then the publisher is responsible for sending a message or taking action on all of the subscribers.

A high-level diagram would look something like this:

WordPress Design Patterns

From a code perspective, the Publisher needs three things:

  1. A way to maintain a list of the subscribers
  2. A way for the subscribers to register themselves
  3. A way to broadcast a message to all of the subscribers

Similarly, the Subscriber needs to be able to do two things:

  1. Register itself with the Publisher
  2. Optionally take action when the Publisher sends a message to it

There are a number of ways in which this can be implemented, but for all intents and purposes and to keep the example relatively simple, let’s say that the Subscribers will register themselves with the Publisher with the Observer’s register method and the function accepts a reference to the Subscriber and each Subscriber has an update method that the Publisher calls when broadcasting the message.

Publisher Code

class MyPublisher 

	/** The list of subscribers that are registered with this publisher */
	private $subscribers;

	/**
	 * Responsible for initializing the class and setting up the list of subscribers.
	 */
	public function __construct() 
		$this->subscribers = array();
	 // end constructor

	/**
	 * Adds the incoming subject to the list of registered subscribers
	 *
	 * @param  array  $subject  The subject to add to the list of subscribers
	 */
	public function register( $subject ) 
		array_push( $this->subscribers, $subject );
	 // end register_subscriber

	/**
	 * Notifies all of the subscribers that something has happened by calling their `update`
	 * method.
	 */
	public function notify_subscribers() 

		for ( $i = 0; $l < count( $this->subscribers ); $i++ ) 

			$current_subscriber = $this->subscribers[ $i ];
			$current_subscriber->update();

		 // end for

	} // end notify_subscribers

} // end class

The code above is about as simple as we can make it:

For those who are more experienced with object-oriented techniques, then you’ll likely see the need for creating a class interface for the Publisher, but that’s outside the scope of this particular tutorial.

Remember, the purpose is to simply provide an example of what a simple observer may look like.

Subscribe Code

Creating a Publisher is really only half of the implementation. Remember, we have to have something that actually, you know, subscribes to the Publisher to take action whenever something happens.

This is where the aptly named Subscriber comes into play.

class MySubscriber 

	/** The publisher to which this class registers */
	private $publisher;

	/**
	 * Responsible for initializing the class and setting up a reference to the publisher
	 */
	public function __construct() 

		$this->publisher = new MyPublisher();
		$this->publisher->register( $this );

	 // end constructor

	/**
	 * This is the method that the Publisher calls when it it broadcasts its message.
	 */
	public function update() 

		/** Implementation is based purely on however you'd like. */

	 // end update

} // end class

In short, this is it. Notice above that this implementation of the update function isn’t actually defined. That’s because it gives us the ability to provide unique behavior to this specific instance.

But remember, there’s a lot of code in WordPress core that is not object-oriented. Instead, it’s procedural. As such, the implementation of a pattern like this varies a little bit.

For example, an analogy in WordPress would be something like this:

function my_custom_subscriber( $content ) 

	$content = 'This is my custom content.' . $content;
	return $content;

 // end my_custom_subscriber
add_action( 'the_content', 'my_custom_subscriber' );

Notice that the syntax is a bit different, but we’re essentially doing a very similar thing:

  • We have a subscribe function – my_custom_subscriber – and it’s registered with the the_content event
  • When the the_content function fires, our custom function will fire.

Nothing too complicated, I hope.

One of the goals in this series is not only to provide a few examples of design patterns and how to implement them, but they are already in place in existing systems.

/>

The Patterns We’ll Examine

In addition to the event-driven pattern that we’ve examined above, we’re also going to take a look at two patterns that are common, practical, and highly useful in our day-to-day work.

Specifically, we’re going to take a look at the following patterns:

  1. Singleton Pattern. In object-oriented design, the Single Pattern ensures that only a single instance of a class is created. This is useful so that we don’t accidentally create multiple instances maintaining their own sets of data ultimately giving conflicting results during a project’s lifecycle.
  2. Simple Factory Pattern. If you have a collection of classes each of which are designed to handle a specific type of data (as opposed to have one large class do it), then the Simple Factory Pattern is useful for taking a look at the incoming data and then returning an instance of the proper class for processing the data.

Obviously, talking about software only goes so far without talking about diagrams and/or code so we’ll be taking a look at both of those in the upcoming set of articles.

/>

Conclusion

As you can see, the concept of design patterns isn’t anything terribly complicated and there’s a lot to be gained by using them in our work. Perhaps the greatest challenge that developers face is using design patterns for the sake of using design patterns.

Instead, it’s important to recognize that there are certain situations in which design patterns are applicable. That is to say that there are certain problems for which design patterns are the perfect solution. Experience is arguably the best teacher for knowing when to use a design pattern and when not to use it.

In the following articles, hopefully we’ll be able to cover enough territory to provide two solid examples of design patterns, when they’re applicable, how to use them, and how they can help us in our future work.

Original from: http://feedproxy.google.com/~r/Wptuts/~3/9OSVpqV7FhY/

Quick Tip: After the Content – More From This Category

May 7th, 2013 Comments off

This entry is part 6 of 6 in the series After the Content

Do you have a solid construction of categories on your blog? If so, you might not need a “Related Posts” section at all – you can just display latest posts from the same category.

In this post, we’re going to go through the “More From This Category” section, an alternative to “Related Posts” (which we covered earlier).

/>

Show You Have More to Say

If you keep your posts organized well with categories, you might find it useful to have a list of posts from the post’s category.

“Related Posts” is not always the answer: If you have a website where the posts are separated with categories, a “Related Posts” section might “break” this separation.

For example, if you have a blog about different occupational groups, you can’t show news about the textile sector as “Related News” under a post about informatics. A number of latest posts from the same category would be more relevant, right?

Creating a “More From This Category” List

As you may have guessed, listing latest posts from a post’s category will be much easier than displaying related posts based on a post’s tags. We just need to get the category of the post and list a number of posts from that category, excluding the post that the visitors have just read. The arguments that we can pass in the get_posts() function has everything we need.

ID );
    $first_cat = $categories[0]->cat_ID;
    // Let's start the $output by displaying the title and opening the 
    $output = '

    ' . $title . '

    '; // The arguments of the post list! $args = array( // It should be in the first category of our post: 'category__in' => array( $first_cat ), // Our post should NOT be in the list: 'post__not_in' => array( $post->ID ), // ...And it should fetch 5 posts - you can change this number if you like: 'posts_per_page' => 5 ); // The get_posts() function $posts = get_posts( $args ); if( $posts ) $output .= '
      '; // Let's start the loop! foreach( $posts as $post ) setup_postdata( $post ); $post_title = get_the_title(); $permalink = get_permalink(); $output .= '
    • ' . $post_title . '
    • '; $output .= '
    '; } else // If there are no posts, we should return something, too! $output .= '

    Sorry, this category has just one post and you just read it!

    '; // Let's close the
    and return the $output: $output .= '
    '; return $output; } ?>

Done! You can include this function inside your functions.php file (or save it as a separate plugin) and echo it (as ) anywhere you want inside your single.php file.

/>

Conclusion

Yes, content may be “king” but a lonely king is a weak king, and people might not respect that “king”.

Do you think there are more page elements that can help “the king”? Post your comments below – it’s always important for you to share your thoughts with us!

Original from: http://feedproxy.google.com/~r/Wptuts/~3/ARIEWv5glFM/

Guide to Creating Your Own WordPress Editor Buttons

April 30th, 2013 Comments off

Most likely you know that WordPress is bundled with the HTML WYSIWYG editor, TinyMCE. The variety of features, and the ability to be extended though plugins, make it the most used WYSIWYG editor in the world. WordPress doesn’t make use of all its features, however. WordPress customizes it and only keeps parts which are really helpful to users, avoiding messing up the user interface. That also means some features, buttons for example, have been hidden from users. You can totally enable the hidden MCE buttons. Typically they are stylesheet, sub, sup buttons. If even the hidden ones still don’t satisfy your needs, then you have to create a TinyMCE plugin to do add your own. In this tutorial, I will walk you through the basics of adding your WordPress Editor buttons by creating a TinyMCE plugin.

/>

Before We Start

As mentioned earlier, we will create a new TinyMCE plugin whose task is to add the new buttons we want. So which buttons are we going to add? We will try to add two simple buttons: Dropcap and Recent Posts, in which the former gives you the ability to convert a selected letter to a drop cap letter, and the latter will display recent posts. The code generates these buttons shown below.

Let’s create a new folder named wptuts-editor-buttons (of course, you can change it to something else if you want) in your theme directory (I’m using TwentyTwelve). Continue to create two new files, wptuts.php that invokes customized PHP, and the other named wptuts-plugin.js where the JavaScript code snippets will be located. Finally, open your theme’s functions.php file and include the newly created wptuts.php file in it. Note, remember to define its path exactly:

require( 'wptuts-editor-buttons/wptuts.php' );

Then we need to prepare some code for those two buttons:

  • Dropcap – The ideal way of making a letter into drop caps is to simply wrap the user’s selected letter within a pre-defined HTML span class which styles that letter to look like drop caps. The CSS code of the class shown below, just appends it to your theme’s style.css file:
    		/* Add this code in style.css */
    		.dropcap 
    			float: left;
    			font-size: 80px;
    			padding-right: 7px;
    			line-height: 72px;
    		
    		
  • Recent Posts – We will make a shortcode that will add a list of recent posts into the page, open the wptuts.php file and add the following code:
    		add_shortcode( 'recent-posts', 'wptuts_recent_posts' );
    		function wptuts_recent_posts( $atts ) 
    			extract( shortcode_atts( array(
    				'numbers' => '5',
    			), $atts ) );
    			$rposts = new WP_Query( array( 'posts_per_page' => $numbers, 'orderby' => 'date' ) );
    			if ( $rposts->have_posts() ) 
    				$html = '

    Recent Posts

      '; while( $rposts->have_posts() ) $rposts->the_post(); $html .= sprintf( '
    • %s
    • ', get_permalink($rposts->post->ID), get_the_title(), get_the_title() ); $html .= '
    '; } wp_reset_query(); return $html; }

    We assume that when users click the Recent Posts button, the browser will popup a dialog asking them for the number of posts they want to show. After having that number, the editor will fill it as an argument into the above shortcode. For example, if we want to show seven recent posts, the shortcode is generated as follows:

    		[recent-posts numbers="7"/]
    		
/>

Registering a New TinyMCE Plugin

Assuming we already had the new plugin, then we need to register it with WordPress to integrate it into the TinyMCE editor. The code is shown below:

add_action( 'init', 'wptuts_buttons' );
function wptuts_buttons() 
	add_filter( "mce_external_plugins", "wptuts_add_buttons" );
	add_filter( 'mce_buttons', 'wptuts_register_buttons' );

function wptuts_add_buttons( $plugin_array ) 
	$plugin_array['wptuts'] = get_template_directory_uri() . '/wptuts-editor-buttons/wptuts-plugin.js';
	return $plugin_array;

function wptuts_register_buttons( $buttons ) 
	array_push( $buttons, 'dropcap', 'showrecent' ); // dropcap', 'recentposts
	return $buttons;

The important filter hook mce_external_plugins is used to hook the new plugin to TinyMCE. We need to pass a plugin ID (wptuts) and the absolute URL pointing to our wptuts-plugin.js file. The mce_buttons hook is used to tell the TinyMCE editor which buttons in our plugin we want to show. The dropcap and showrecent are the ID values of these buttons that we plan to create. Keep in mind these values, they will be used later.

/>

Setting Up TinyMCE Plugin

In general, I think the best way to extend or develop something on a platform is to consult the documentation for that platform. TinyMCE has its own wiki that you might find useful. By following an example of how to create a TinyMCE plugin, we have the following initialisation code:

(function() 
	tinymce.create('tinymce.plugins.Wptuts', 
		/**
		 * Initializes the plugin, this will be executed after the plugin has been created.
		 * This call is done before the editor instance has finished it's initialization so use the onInit event
		 * of the editor instance to intercept that event.
		 *
		 * @param tinymce.Editor ed Editor instance that the plugin is initialized in.
		 * @param string url Absolute URL to where the plugin is located.
		 */
		init : function(ed, url) 

		,

		/**
		 * Creates control instances based in the incomming name. This method is normally not
		 * needed since the addButton method of the tinymce.Editor class is a more easy way of adding buttons
		 * but you sometimes need to create more complex controls like listboxes, split buttons etc then this
		 * method can be used to create those.
		 *
		 * @param String n Name of the control to create.
		 * @param tinymce.ControlManager cm Control manager to use inorder to create new control.
		 * @return tinymce.ui.Control New control instance or null if no control was created.
		 */
		createControl : function(n, cm) 
			return null;
		,

		/**
		 * Returns information about the plugin as a name/value array.
		 * The current keys are longname, author, authorurl, infourl and version.
		 *
		 * @return Object Name/value array containing information about the plugin.
		 */
		getInfo : function() 
			return 
				longname : 'Wptuts Buttons',
				author : 'Lee',
				authorurl : 'http://wp.tutsplus.com/author/leepham',
				infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/example',
				version : "0.1"
			;
		}
	});

	// Register plugin
	tinymce.PluginManager.add( 'wptuts', tinymce.plugins.Wptuts );
})();

Remember to add this code into the wptuts-plugin.js file. We’ve left the code comments for you to easily understand what’s going on. The above code just does two main tasks:

  1. First, defining a new TinyMCE plugin in a safe way by calling TinyMCE’s create method. Our plugin’s behavior will be defined in the init and createControl functions. You can see that the plugin’s information is declared in the getInfo function too. Our plugin will have the name Wptuts and the ID wptuts as you can see.
  2. Last, simply add our new plugin into the TinyMCE Plugin Manager.
/>

Creating Buttons

In the init function, we start to create our buttons. The code seen as follows:

(function() 
	tinymce.create('tinymce.plugins.Wptuts', 
		init : function(ed, url) 
			ed.addButton('dropcap', 
				title : 'DropCap',
				cmd : 'dropcap',
				image : url + '/dropcap.jpg'
			);

			ed.addButton('showrecent', 
				title : 'Add recent posts shortcode',
				cmd : 'showrecent',
				image : url + '/recent.jpg'
			);
		},
		// ... Hidden code
	});
	// Register plugin
	tinymce.PluginManager.add( 'wptuts', tinymce.plugins.Wptuts );
})();

By using the addButton method of the ed object, we tell the current editor that we want to create all these buttons. This method accepts two arguments:

  • The first one is the button’s ID. In the previous section, we mentioned it. It must be the same as the one we defined before. Otherwise, it will not work properly.
  • The second one is the object containing the button’s information, such as:
    • The button’s title
    • The most important: the task that the button will do. Take a look at the cmd property, it has the value of showrecent. That is the command’s ID which is executed every time it is called, we will go into detail shortly
    • The image of the button. Note that the URL parameter holds the absolute directory’s URL in which our plugin is located, this makes it easier to reference the image that you want. So you need to place your image into the plugin’s folder and ensure its name to is set precisely to the image‘s value.

Now, check the WordPress editor and we will see our buttons showing up. However, they do nothing right now.

Guide-To-Creating-Your-Own-WPs-Editor-Buttons-1 />
Our buttons showed up.
/>

Adding Buttons’ Commands

We’ve defined the name of the commands our buttons will execute, but have not yet defined what they will actually run. In this step, we will set up the things our buttons will do. Inside the init function, continue to add this code as shown:

(function() 
	tinymce.create('tinymce.plugins.Wptuts', 
		init : function(ed, url) 
			ed.addButton('dropcap', 
				title : 'DropCap',
				cmd : 'dropcap',
				image : url + '/dropcap.jpg'
			);

			ed.addButton('showrecent', 
				title : 'Add recent posts shortcode',
				cmd : 'showrecent',
				image : url + '/recent.jpg'
			);

			ed.addCommand('dropcap', function() 
				var selected_text = ed.selection.getContent();
				var return_text = '';
				return_text = '' + selected_text + '';
				ed.execCommand('mceInsertContent', 0, return_text);
			);

			ed.addCommand('showrecent', function() 
				var number = prompt("How many posts you want to show ? "),
					shortcode;
				if (number !== null) 
					number = parseInt(number);
					if (number > 0 && number <= 20) 
						shortcode = '[recent-post number="' + number + '"/]';
						ed.execCommand('mceInsertContent', 0, shortcode);
					
					else 
						alert("The number value is invalid. It should be from 0 to 20.");
					
				}
			});
		},
		// ... Hidden code
	});
	// Register plugin
	tinymce.PluginManager.add( 'wptuts', tinymce.plugins.Wptuts );
})();

Now, the ed.addCommand method will help us to add a new command. You need to pass the command’s ID and the callback function that will be executed if it was called by the ed.execCommand method. Note that ed represents the tinyMCE.activeEditor object. Let’s take a look at the callback functions:

  • In the dropcap command, the desire we want is when a user selects a letter and clicks the DropCap button, the letter will then be transformed to drop cap form. So how do we get that letter? Well, the ed.selection.getContent method will do that for us. Next, once we’ve gotten that letter we just wrap it within a span element. Remember to set this element’s class value to dropcap that we’ve defined before, right? Finally, we have the complete text that needs to be inserted back into the editor. TinyMCE has a default command with the name mceInsertContent which is used to insert specific content into the editor, how to use it is shown above. The content will be passed as the third argument of the mceInsertContent method.
  • A similar thing happens in the showrecent command as in the dropcap command, excepting we don’t need to get the user’s selected content. We just simply display a dialog asking the user how many posts they want to show up, then insert that number value in an appropriate shortcode syntax.

Registering Custom CSS for Buttons (Optionally)

Instead of adding pure text when the buttons insert contents into the visual editor, we can make it much more visual by registering custom CSS for our buttons. It depends on which type of content data, and you can choose an appropriate style. For example, our Dropcap‘s style can have the same as the one showing on the front-end. So you can take its CSS code in the very top of this post, then place it into the editor-style.css file (for default, see add_editor_style for detais).

For shortcodes, they might not have an HTML element themselves. How should we style them? Well, this situation is much more complex to achieve the result, it’s not impossible though (you can see some default WordPress button such as ‘Add media’). However, it can still be a tricky, by wrapping that shortcode in a HTML element and then styling that element just like above. It’s quite simple, not completely perfect though. In this post, we won’t focus on that complex processing.

/>

Results

Finally, the results we get are shown as following:

Test-the-Dropcap-button. />
Test the Dropcap button.

Then, on the front-end:

Dropcap-letter-in-front-end. />
Dropcap letter in front-end.

And the Recent Posts button works well too:

Recent-Posts-button-worked. />
Recent Posts button worked.
/>

Conclusion

Okay, we covered a practice which is quite simple and easy to follow. You might notice that the Recent Posts button allows you to adjust a setting (the number of posts that will show). You certainly know that we used the default JavaScript, prompt, to achieve that. What if you want a more complex popup, which has many settings rather than only one? Well, in another post we will discuss this and try another approach.

Any feedback about this post will be appreciated. Thanks for reading, and see you later.

/>

Reference

Original from: http://feedproxy.google.com/~r/Wptuts/~3/smdREbjvZMo/

How to Modify the Parent Theme Behavior Within the Child Theme

April 26th, 2013 Comments off

What are child themes? Child themes are a useful WordPress feature that allows developers to build a new template without starting from scratch, but by taking advantage of all the features already available in an existing theme.

Sometimes however, the parent theme we have chosen for our site may have some features that we don’t need (or we need to customize to best suit our needs), for example custom post types with a different slug, Shortcodes, JavaScript libraries, image sizes that we don’t use and so on…

/>

Customize the Theme in Two Ways

While it could be easy to achieve what we want by editing the theme directly, it is also true that everytime the theme will be updated we’ll have to do all the customizations again. This can be frustrating, so there’s another option: we can create a child theme and use the >functions.php> file to modify the parent theme features. In this way we can upgrade the parent theme everytime a new version is released without losing our customizations.

Before we step into more specific details, a brief note about the theme appearance: we can modify colors, backgrounds, typography and the layout through the style.css file of the child theme by importing the parent style.css and overriding the styles we want to change.

For more control on the layout, we can also follow how Abbas Suterwala suggests in his post and clone the parent custom template files in our child theme:

Then the child theme could optionally override other template files like author.php, category.php, etc. The WordPress framework first looks for a template file in the child theme directory and then if not found will pick it up from the parent directory.

/>

What We Can Modify

Through the child theme’s functions.php file we can deal with:

  • Theme features
  • Custom post types and taxonomies
  • Menus and sidebars
  • Widgets
  • Shortcodes
  • Additional image sizes
  • Metaboxes
  • JavaScript and CSS
  • Parent theme actions and filters

So, let’s say we have this web site structure:

  • htdocs OR www
    • wp-content
      • themes
        • foo-theme (directory of the parent theme – it will not be modified)
          • functions.php
          • header.php
          • style.css
          • other template files…
        • foo-theme-child (directory of our child theme)
          • functions.php (the file we will use to customize the parent theme)
          • header.php (overrides header.php for the parent theme)
          • style.css (this is a required file in a child theme and must be named style.css)

Let’s get started: create an empty functions.php file in the /wp-content/themes/foo-theme-child/ directory.

For the most part we will use a generic wp_tuts_remove_features() function, hooked to the WordPress after_setup_theme action. We also set 10 as a third parameter (priority), so we are sure that the function is triggered before the parent one.

add_action( 'after_setup_theme', 'remove_parent_theme_features', 10 );

function remove_parent_theme_features() 
	// our code here

/>

1. Remove Theme Features

Some parent themes add features to WordPress through the add_theme_support function.

Available features are:

  • post-formats
  • post-thumbnails
  • custom-background
  • custom-header
  • automatic-feed-links

So to remove them, we can modify the remove_parent_theme_features() function in the functions.php file.

function remove_parent_theme_features() 
	remove_theme_support( 'post-formats' );
	remove_theme_support( 'post-thumbnails' );
	remove_theme_support( 'custom-background' );
	remove_theme_support( 'custom-header' );
	remove_theme_support( 'automatic-feed-links' );

/>

2. Remove Custom Post Types and Taxonomies

Removing custom post types and custom taxonomies is easy: if the parent functions.php file adds a Movie custom post type, through a parent_movie_add_post_type() function:

// PARENT functions.php

add_action( 'after_setup_theme', 'parent_movie_add_post_type' );

function parent_movie_add_post_type() 

	$parent_args = array(
		// other arguments...
		'rewrite' => array( 'slug' => 'movie' ),
		'supports' => array( 'title', 'editor', 'author', 'excerpt' )
	);
	register_post_type( 'movie', $parent_args );

… we can customize it thanks to our child functions.php file:

// CHILD functions.php

function remove_parent_theme_features() 
	// remove Movie Custom Post Type
	remove_action( 'init', 'parent_movie_add_post_type' );
	/*
	alternatively, we can add our custom post type to 
	overwrite only some aspects of the parent function
	*/
	add_action( 'init', 'child_movie_post_type' );


function child_movie_post_type() 
	$child_args = array(
		// other arguments...
		// change Custom Post slug
		'rewrite' => array( 'slug' => 'child-movie' ),
		// remove excerpts and add post thumbs
		'supports' => array( 'title', 'editor', 'author', 'thumbnail' )
	);

	register_post_type( 'movie', $child_args );

We can also remove only certain features without unregistering the post type, for example if we want to replace the excerpt field with a post featured image, we can modify the function in this way:

function remove_parent_theme_features() 
	add_action( 'init', 'wp_tuts_remove_post_feature' );


function wp_tuts_remove_post_feature() 
	// remove excerpt
	remove_post_type_support( 'movie', 'excerpt' );
	// add post thumbs
	add_post_type_support( 'movie', 'thumbnail' );

You can find a complete list of removable features under remove_post_type_support in the WordPress Codex.

Similar to custom post types, you can remove a custom taxonomy added in the parent theme by a parent_taxonomy() function, in this way:

function wp_tuts_after_setup_theme() 
	remove_action( 'init', 'parent_taxonomy' );

/>

3. Remove Menus

We can remove a parent theme’s menu through the unregister_nav_menu() function. This function takes one parameter, the menu location identifier slug used in the register_nav_menu() function.

If the parent theme registers a Header Menu:

// PARENT functions.php

add_action( 'after_setup_theme', 'register_my_menu' );

function register_my_menu() 
	register_nav_menu( 'header-menu', __( 'Header Menu' ) );

We can remove it in this way:

// CHILD functions.php

function remove_parent_theme_features() 
	unregister_nav_menu( 'header-menu' );

To identify registered menus, we can search the parent theme code for register_nav_menu() calls. The first argument of the function represents the menu ID we can use to unregister (in this case header-menu).

/>

4. Remove Widgets and Sidebars

WordPress comes with some default Widgets that we can deactivate. Also, our parent theme could add its own widgets, so we can search in the theme files looking for where they are declared and take note of their name. Usually they are declared in a PHP class that extends the WP_Widget class:

// PARENT theme
class ParentWidgetName extends WP_Widget 
	// widget code

So, to unregister the widget, we use the class name ParentWidgetName:

add_action( 'widgets_init', 'wp_tuts_parent_unregister_widgets', 10 );

function wp_tuts_parent_unregister_widgets() 

	// remove (some) WordPress default Widgets
	unregister_widget( 'WP_Widget_Pages' );
	unregister_widget( 'WP_Widget_Calendar' );

	// remove Parent registered Widget
	unregister_widget( 'ParentWidgetName' );

	// register a custom Widget (if needed)
	register_widget( 'MyCustomWidget' );


// don't forget to add the Widget Class
class MyCustomWidget extends WP_Widget 
	// Custom Widget code

For sidebars the action is similar:

add_action( 'widgets_init', 'wp_tuts_parent_unregister_sidebars', 10 );

function wp_tuts_parent_unregister_sidebars() 
	// remove a sidebar registered by the Parent Theme
	unregister_sidebar( 'first-footer-widget-area' );

To identify registered sidebars, we can search the parent theme’s code for register_sidebar() calls.

All we need is to take note of the sidebar ID:

// PARENT functions.php

$args = array(
	'id' => 'first-footer-widget-area',
	// other args...
);

register_sidebar( $args );
/>

5. Remove Shortcodes

Overriding or removing shortcodes is easy, we only need to modify our function in this way:

function remove_parent_theme_features() 
	// remove the parent [gmap] shortcode
	remove_shortcode( 'gmap' );
	// add our [gmap] shortcode
	add_shortcode( 'gmap', 'child_shortcode_gmap' );


function child_shortcode_gmap( $atts ) 
	// create our shortcode that overwrites the parent one

To identify registered shortcodes, we can search the parent theme code for add_shortcode() calls. The first parameter is the one we’re after ;-) .

/>

6. Remove Additional Image Sizes

If the parent theme adds new image sizes that we don’t use in our child theme, we can search the parent theme code for add_image_size() calls. In this case they are: custom_size_parent_1 and custom_size_parent_2. We reset them in this way:

add_filter( 'intermediate_image_sizes_advanced', 'remove_parent_image_sizes' );

function remove_parent_image_sizes( $sizes ) 
	unset( $sizes['custom_size_parent_1'] );
	unset( $sizes['custom_size_parent_2'] );
	return $sizes;

This is useful because every time the user uploads an image, WordPress will not create additional image sizes that we don’t use.

To create custom image sizes we can add this in our child functions.php file:

if ( function_exists( 'add_image_size' ) ) 
	// 400 pixels wide and unlimited height
	add_image_size( 'custom_size_child_1', 400, 9999 );
	// 320 pixels wide and 240 px tall, cropped
	add_image_size( 'custom_size_child_2', 320, 240, true );

/>

7. Remove Metaboxes

Through the remove_meta_box() function we can remove both default WordPress and parent theme metaboxes.

A list of WordPress default metaboxes is available under remove_meta_box() in the WordPress Codex. The function has three arguments: the metabox ID, the page it will be removed from, the editing context (normal, advanced, side).

If the parent theme adds metaboxes in the post editing screen, we can disable them in this way:

add_action( 'admin_menu' , 'wp_tuts_remove_metaboxes', 99 );

function wp_tuts_remove_metaboxes() 
	// remove default WP Trackback Metabox from Posts editing page
	remove_meta_box( 'trackbacksdiv', 'post', 'normal' );
	// remove a Parent Theme Metabox 'parent_post_foo_metabox'
	remove_meta_box( 'parent_post_foo_metabox', 'post', 'normal' );

We can identify parent metaboxes by searching the parent theme code for add_meta_box or add_meta_boxes() calls.

The ID of the metabox to remove is the first argument of the add_meta_box() function.

/>

8. Remove JavaScripts and CSS Stylesheets

If the parent theme adds JavaScript and CSS styles that we don’t need:

// PARENT functions.php

add_action( 'wp_print_scripts', 'parent_scripts' );
add_action( 'wp_print_styles', 'parent_styles' );

function parent_scripts() 
	wp_enqueue_script( 'fancybox-parent-js', get_stylesheet_directory_uri() . '/fancybox/jquery.fancybox.pack.js' );


function parent_styles() 
	wp_enqueue_style( 'fancybox-parent-css', get_stylesheet_directory_uri() . '/fancybox/jquery.fancybox.css' );

We can remove them in this way:

// CHILD functions.php

add_action( 'wp_print_scripts', 'child_overwrite_scripts', 100 );
add_action( 'wp_print_styles', 'child_overwrite_styles', 100 );

function child_overwrite_scripts() 
	wp_deregister_script( 'fancybox-parent-js' );


function child_overwrite_styles() 
	wp_deregister_style( 'fancybox-parent-css' );

To identify registered JavaScripts and CSS styles, we can search the parent theme code for wp_enqueue_script() and wp_enqueue_style() calls.

The first argument of the function is what we can use in the wp_deregister_script() or wp_deregister_style() functions.

/>

9. Remove Parent Theme Actions and Filters

Some themes, like Thematic provide several hooks to modify the theme behavior without altering the theme files. In this case, Thematic provides a thematic_header action that loads other actions:

  • thematic_brandingopen()
  • thematic_blogtitle()
  • thematic_blogdescription()
  • thematic_brandingclose()
  • thematic_access()

We will not examine in detail what these functions do, probably some of them print some info in the blog header: name, description, and so on… In this case we can deactivate the thematic_blogdescription() function in this way:

// Unhook default Thematic functions
function unhook_thematic_functions() 
	// we put the position number of the original function (5)
	// for priority reasons
	remove_action( 'thematic_header', 'thematic_blogdescription', 5 );

add_action( 'init', 'unhook_thematic_functions' );

In these cases it can be hard to understand the structure of the parent theme and how it works. My advice is to choose a parent theme that ships with detailed documentation, a good support forum, and makes hooks available throughout the code.

This surely makes us lose less developement time and make the customization of the child theme easier.

/>

References

Original from: http://feedproxy.google.com/~r/Wptuts/~3/UUx5xv0GD1k/

Multiple Shortcodes With a Single Function: 3 Killer Examples

April 8th, 2013 Comments off

The powerful Shortcode API allows us to create “snippets” and include special content (such as PHP functions or complex HTML code) in our posts. It’s extremely common to build separate functions for each shortcode, but is it really necessary? In this post, we’re going to see how we can utilize more than one shortcode by building a single function.

/>

In Defense of Shortcodes

The APIs make WordPress one of the most flexible content management systems of all. They are the reason why there are tens of thousands of plugins and themes out there: The huge community of WordPress is capable of making WordPress do backflips and cartwheels, thanks to the APIs of WordPress.

Among these APIs, my favorite is the Shortcode API. Its logic and validity is being questioned but I strongly believe that using shortcodes in WordPress has an easy learning curve and once they are learned those few easy rules about parameters and opening/closing tags, even novice users can enjoy using shortcodes. Correct, it’s not WYSIWYG but a WordPress newbie may have a harder time to clear the mess if they did something wrong in a WYSIWYG editor and ruined the HTML. Easier to see that the shortcode doesn’t work, delete it, and type it again.

But of course, it’s just an opinion of mine. Let’s get back to the subject: We’re building multiple shortcodes with a single function!

/>

The Benefit of This Technique

There’s really no need to argue the benefit of this method – consider this ridiculously long example:

 '',
		'last' => ''
	), $atts ) );
	if ( $class != '' )
		$class = ' ' . $class;
	if ( $last = 'yes' )
		$last_class = ' last';
	return '
' . do_shortcode( $content ) . '
'; add_shortcode( 'one_half', 'one_half_sc' ); function one_third_sc( $atts, $content = null, $tag ) extract( shortcode_atts( array( // extra classes 'class' => '', 'last' => '' ), $atts ) ); if ( $class != '' ) $class = ' ' . $class; if ( $last = 'yes' ) $last_class = ' last'; return '
' . do_shortcode( $content ) . '
'; add_shortcode( 'one_third', 'one_third_sc' ); function one_quarter_sc( $atts, $content = null, $tag ) extract( shortcode_atts( array( // extra classes 'class' => '', 'last' => '' ), $atts ) ); if ( $class != '' ) $class = ' ' . $class; if ( $last = 'yes' ) $last_class = ' last'; return '
' . do_shortcode( $content ) . '
'; add_shortcode( 'one_quarter', 'one_quarter_sc' ); function two_thirds_sc( $atts, $content = null, $tag ) extract( shortcode_atts( array( // extra classes 'class' => '', 'last' => '' ), $atts ) ); if( $class != '' ) $class = ' ' . $class; if( $last = 'yes' ) $last_class = ' last'; return '
' . do_shortcode( $content ) . '
'; add_shortcode( 'two_thirds', 'two_thirds_sc' ); function three_quarters_sc( $atts, $content = null, $tag ) extract( shortcode_atts( array( // extra classes 'class' => '', 'last' => '' ), $atts ) ); if ( $class != '' ) $class = ' ' . $class; if ( $last = 'yes' ) $last_class = ' last'; return '
' . do_shortcode( $content ) . '
'; add_shortcode( 'three_quarters', 'three_quarters_sc' ); ?>

The same code (both PHP and HTML) is being used over and over again in every single function – except the varying CSS classes. Plus, the attributes in each function are the same as in the other functions. It’s just hard to read. Come to think of it, if we ever had to change a feature of these column divs, we would have to change the same parts in all of the functions.

What if there was a variable to fetch the “tag” of the shortcode? Not so surprisingly, the variable is called $tag and could be used inside our functions. It allows our functions to check the tag of the shortcode and behave according to the tag.

Think about the example above: If there is more than one function that serves almost the same functionality, it would be logical (and pretty cool) to have one function for our shortcodes to use.

I’ve come up with three good examples on how we can use this technique. If you can think of more while reading the post, you’re welcome to share your thoughts with everyone else on the comments section below!

/>

Example 1 Video Embeds

In one of my earliest posts on Wptuts+, I explained how to use a shortcode to embed videos from various video hosts like YouTube, Vimeo and Dailymotion. The code looked like this:

 'youtube',
			'id' => '',
			'w' => '600',
			'h' => '370'
		), $atts )
	);
	if ( $site == "youtube" )  $src = 'http://www.youtube-nocookie.com/embed/' . $id; 
	else if ( $site == "vimeo" )  $src = 'http://player.vimeo.com/video/' . $id; 
	else if ( $site == "dailymotion" )  $src = 'http://www.dailymotion.com/embed/video/' . $id; 
	else if ( $site == "yahoo" )  $src = 'http://d.yimg.com/nl/vyc/site/player.html#vid=' . $id; 
	else if ( $site == "bliptv" )  $src = 'http://a.blip.tv/scripts/shoggplayer.html#file=http://blip.tv/rss/flash/' . $id; 
	else if ( $site == "veoh" )  $src = 'http://www.veoh.com/static/swf/veoh/SPL.swf?videoAutoPlay=0&permalinkId=' . $id; 
	else if ( $site == "viddler" )  $src = 'http://www.viddler.com/simple/' . $id; 
	if ( $id != '' ) 
		return '';
	
}
add_shortcode( 'vid', 'vid_sc' );
?>

While it’s still a not-so-bad practice (except the 6 else if statements), we can now use one less attribute (‘site‘) and create separate shortcodes, like this:

 '',
		'w' => '600',
		'h' => '370'
	), $atts ) );
	switch( $tag ) 
		case "youtube":
			$src = 'http://www.youtube-nocookie.com/embed/';
			break;
		case "vimeo":
			$src = 'http://player.vimeo.com/video/';
			break;
		case "viddler":
			$src = 'http://www.viddler.com/simple/';
			break;
		case "dailymotion":
			$src = 'http://www.dailymotion.com/embed/video/';
			break;
	
	if ( $id != '' )
		return '';
	return;
}
add_shortcode( 'youtube', 'wptuts_embed_sc' );
add_shortcode( 'vimeo', 'wptuts_embed_sc' );
add_shortcode( 'viddler', 'wptuts_embed_sc' );
add_shortcode( 'dailymotion', 'wptuts_embed_sc' );
?>

See what we did? We provided a $tag parameter for our function in the first line (to replace the “site” attribute) and used a switch conditional statement (for the sake of better, cleaner code). The result for the two functions will be the same, except you can use [youtube id="..."] instead of [vid site="youtube" id="..."] now.

(I didn’t use some of the video hosts in the second function. If you need to add more hosts, you can add as many “case“s as you like.)

/>

Example 2 Column divs

Ah, columns… they’re the most important part of a CSS grid, and they make it super easy to make your website more adaptive, if they support responsive design techniques. You can see them in almost every WordPress theme on ThemeForest and they use shortcodes… with a practice like our “ridiculously long example” at the beginning of this tutorial.

As you remember, the code was almost the same in all 5 functions in that example. Thus, it would be incredibly easy to merge them into one single function and let the $tag variable work its magic:

 ''
	), $atts ) );
	if ( $class != '' )
		$class = ' ' . $class;
	$last = '';
	// check the shortcode tag to add a "last" class
	if ( strpos( $tag, '_last' ) === true )
		$last = ' last';
	$output = '
' . do_shortcode( $content ) . '
'; return $output; add_shortcode( 'one_half', 'wptuts_columns_sc' ); add_shortcode( 'one_half_last', 'wptuts_columns_sc' ); add_shortcode( 'one_third', 'wptuts_columns_sc' ); add_shortcode( 'one_third_last', 'wptuts_columns_sc' ); add_shortcode( 'one_quarter', 'wptuts_columns_sc' ); add_shortcode( 'one_quarter_last', 'wptuts_columns_sc' ); add_shortcode( 'two_thirds', 'wptuts_columns_sc' ); add_shortcode( 'two_thirds_last', 'wptuts_columns_sc' ); add_shortcode( 'three_quarters', 'wptuts_columns_sc' ); add_shortcode( 'three_quarters_last', 'wptuts_columns_sc' ); ?>

Pretty neat, right? We didn’t even need to use a switch!

We still duplicate lines while adding the shortcodes, though. Dare to go one step further? Remove the add_shortcode() lines to replace with this:


Now we have even more maintainable code. For example; if we were to change the name of the function, we wouldn’t bother to change every line anymore.

/>

Example 3 Post Lists

Ever needed to list some previous (or future) articles in your posts? I certainly do. There are loads of plugins which provide shortcodes but most of them require you to use tons of attributes which can result in some ugly, complex tag like [posts cat="5,6" author="barisunver" status="private" postsperpage="4" and="so on"].

How about we use our beloved $tag instead? Let’s give it a shot:

ID;
	$post_author = $post->post_author;
	extract( shortcode_atts(  array(
		'number' => 5,
		'exclude_current' => 'yes',
		'orderby' => 'date'
	), $atts ) );
	$args = '';
	switch( $tag ) 
		case "latest_posts":
			// we don't need any arguments to retrieve latest posts :) 
			break;
		case "category_posts":
			$categories = get_the_category( $post_ID );
			$first_category = $categories[0]->term_id;
			$args = 'cat=' . $first_category;
			break;
		case "author_posts":
			$args = 'author=' . $post_author;
			break;
		case "future_posts":
			$args = 'post_status=future';
			break;
	
	$not_in = '&post__not_in[]=' . $post_ID;
	if ( $exclude_current == 'no' )
		$not_in = '';
	$get_posts = get_posts( $args . $not_in . '&posts_per_page=' . $number . '&orderby=' . $orderby );
	$output = '';
	wp_reset_query();
	return $output;
}
add_shortcode( 'latest_posts', 'wptuts_post_lists_sc' );
add_shortcode( 'category_posts', 'wptuts_post_lists_sc' );
add_shortcode( 'author_posts', 'wptuts_post_lists_sc' );
add_shortcode( 'future_posts', 'wptuts_post_lists_sc' );
?>

As you can see, we can get rid of 3 possible shortcode attributes: “cat“, “author” and “post_status“. You can always extend the cases and add new shortcodes with this single, relatively small function.

/>

Wrapping Up

As a fan of WordPress shortcodes, this discovery of the $tag variable is kind of exciting for me. It seems like there’s a huge potential to utilize this method.

What do you think about this technique? Post your comments below and share your thoughts with us!

Original from: http://feedproxy.google.com/~r/Wptuts/~3/1HAJReKslB0/

Enhancing the Search Form With typeahead.js

April 4th, 2013 Comments off

The WordPress search form doesn’t offer any bells and whistles by default. If it’s already included in your theme, or you’ve added the search widget to one of your sidebars, you can attest to that. One way to greatly improve its functionality is to include an autocomplete script to help enhance the efficiency of how relevant search queries are relayed.

/>

Twitter typeahead.js

There are quite a few autocomplete scripts available and recently Jake Harding from Twitter released typeahead.js, a completely independent version of a similarly named script that comes packaged with Bootstrap. I thought it would be interesting to figure out how to use this lightweight script with WordPress, and after a bit of fumbling around, I managed to put together a little plugin with the help of Michal Bluma.

/>

WP Typeahead Plugin

The plugin is pretty straightforward since there’s only a little bit of customization that is needed to get things working properly. I’ll break down each section of the plugin code for you to explain what’s going on.

Basic Plugin Setup

plugin_url = plugin_dir_url( __FILE__ );

		add_action( 'wp_enqueue_scripts', array( $this, 'wp_enqueue_scripts' ) );

		add_action( 'wp_ajax_nopriv_ajax_search', array( $this, 'ajax_search' ) );
		add_action( 'wp_ajax_ajax_search', array( $this, 'ajax_search' ) );
	
}
$bavotasan_wp_typeahead = new Bavotasan_WP_Typeahead;

On its own, the above code will only spit out some errors but this is the start of everything that you need to use typeahead.js with the WordPress search form. The first action is there to enqueue the JavaScript / CSS files you need and place the required JS in the footer. Next come the Ajax calls to help out with the search results. Let’s take a look at each function.

Enqueueing

/**
 * Enqueue Typeahead.js and the stylesheet
 *
 * @since 1.0.0
 */
public function wp_enqueue_scripts() 
	wp_enqueue_script( 'wp_typeahead_js', $this->plugin_url . 'js/typeahead.min.js', array( 'jquery' ), '', true );
	wp_enqueue_script( 'wp_hogan_js' , $this->plugin_url . 'js/hogan.min.js', array( 'wp_typeahead_js' ), '', true );

	wp_enqueue_script( 'typeahead_wp_plugin' , $this->plugin_url . 'js/wp-typeahead.js', array( 'wp_typeahead_js', 'wp_hogan_js' ), '', true );
	$wp_typeahead_vars = array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) );
	wp_localize_script( 'typeahead_wp_plugin', 'wp_typeahead', $wp_typeahead_vars );

	wp_enqueue_style( 'wp_typeahead_css', $this->plugin_url . 'css/typeahead.css' );

There are four files that need to be enqueued. First is the actual typeahead.js file, then the templating engine called hogan.js, followed by a new JavaScript file we’ll create to put everything in motion, and finally the stylesheet that makes it all look good.

You’ll notice in the middle there we also use wp_localize_script to make the Ajax URL available for our JavaScript.

The Footer Script

( function($) 
	$( 'input[name="s"]' )
		.typeahead( 
			name: 'search',
			remote: wp_typeahead.ajaxurl + '?action=ajax_search&fn=get_ajax_search&terms=%QUERY',
			template: [
				'

value}

', ].join(''), engine: Hogan } ) .keypress( function(e) if ( 13 == e.which ) $(this).parents( 'form' ).submit(); return false; } ); } )(jQuery);

Put this into the new /js/wp-typeahead.js file. The jQuery selector above will attach the typeahead function to any of the default WordPress search forms and use the Hogan templating engine to format the returned Ajax data. Sometimes, the search form can be modified by your theme and the submit button will be removed so I’ve added in a little script to make sure that when you hit the enter button, the search form is actually submitted.

The Ajax Query

/**
 * Ajax query for the search
 *
 * @since 1.0.0
 */
public function ajax_search() 
	if ( isset( $_REQUEST['fn'] ) && 'get_ajax_search' == $_REQUEST['fn'] ) 
		$search_query = new WP_Query( array(
			's' => $_REQUEST['terms'],
			'posts_per_page' => 10,
			'no_found_rows' => true,
		) );

		$results = array( );
		if ( $search_query->get_posts() ) 
			foreach ( $search_query->get_posts() as $the_post ) 
				$title = get_the_title( $the_post->ID );
				$results[] = array(
					'value' => $title,
					'url' => get_permalink( $the_post->ID ),
					'tokens' => explode( ' ', $title ),
				);
			
		} else 
			$results[] = __( 'Sorry. No results match your search.', 'wp-typeahead' );
		

		wp_reset_postdata();
		echo json_encode( $results );
	}
	die();
}

When something is typed into the search form, typeahead.js will take it and submit it through Ajax using the remote parameter from the code in the last step. That text has to pass through a function in order for it to be useful and that’s why you need the little snippet above.

It takes the search text, runs it through a WordPress query to return any relavent results if they exist. Those results are sent back after being encoded using JSON so that the script can read the data properly.

/>

The Completed Code

With everything in place, the main plugin file should look like this…

plugin_url = plugin_dir_url( __FILE__ );

		add_action( 'wp_enqueue_scripts', array( $this, 'wp_enqueue_scripts' ) );

		add_action( 'wp_ajax_nopriv_ajax_search', array( $this, 'ajax_search' ) );
		add_action( 'wp_ajax_ajax_search', array( $this, 'ajax_search' ) );
	

	/**
	 * Enqueue Typeahead.js and the stylesheet
	 *
	 * @since 1.0.0
	 */
	public function wp_enqueue_scripts() 
		wp_enqueue_script( 'wp_typeahead_js', $this->plugin_url . 'js/typeahead.min.js', array( 'jquery' ), '', true );
		wp_enqueue_script( 'wp_hogan_js' , $this->plugin_url . 'js/hogan.min.js', array( 'wp_typeahead_js' ), '', true );
		wp_enqueue_script( 'typeahead_wp_plugin' , $this->plugin_url . 'js/wp-typeahead.js', array( 'wp_typeahead_js', 'wp_hogan_js' ), '', true );

		$wp_typeahead_vars = array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) );
		wp_localize_script( 'typeahead_wp_plugin', 'wp_typeahead', $wp_typeahead_vars );

		wp_enqueue_style( 'wp_typeahead_css', $this->plugin_url . 'css/typeahead.css' );
	

	/**
	 * Ajax query for the search
	 *
	 * @since 1.0.0
	 */
	public function ajax_search() 
		if ( isset( $_REQUEST['fn'] ) && 'get_ajax_search' == $_REQUEST['fn'] ) 
			$search_query = new WP_Query( array(
				's' => $_REQUEST['terms'],
				'posts_per_page' => 10,
				'no_found_rows' => true,
			) );

			$results = array( );
			if ( $search_query->get_posts() ) 
				foreach ( $search_query->get_posts() as $the_post ) 
					$title = get_the_title( $the_post->ID );
					$results[] = array(
						'value' => $title,
						'url' => get_permalink( $the_post->ID ),
						'tokens' => explode( ' ', $title ),
					);
				
			} else 
				$results[] = __( 'Sorry. No results match your search.', 'wp-typeahead' );
			

			wp_reset_postdata();
			echo json_encode( $results );
		}
		die();
	}
}
$bavotasan_wp_typeahead = new Bavotasan_WP_Typeahead;

When you download the plugin, you’ll have the stylesheet and required JS files included within the ZIP file.

/>

Conclusion

Adding an autocomplete script to your search form can help your users navigate through your site more easily. That means a better overall experience which will hopefully lead to more repeat visits and higher traffic. This plugin just needs to be activated in order for it to work with your search forms.

If you have any comments or feedback on anything you read above, please feel free to discuss it below.

Original from: http://feedproxy.google.com/~r/Wptuts/~3/p0PvD5csT4U/

How to Customize Theme Check for Validating WordPress Themes

April 3rd, 2013 Comments off

Security and consistency are some of the major concerns we have in using third party libraries, frameworks and plugins. We face the same problem in using free and commercial WordPress themes and plugins.

The WordPress Codex provides a set of guidelines and rules for developing themes. In order to submit themes to the WordPress theme directory, you have to adhere to those guidelines. But there are hundreds of free and commercial themes which might not be developed according to these guidelines.

Basically we have to check whether a theme matches at least the given set of guidelines and rules. Theme Check is a free WordPress plugin developed to validate WordPress themes.

/>

Can Theme Check Validate Everything?

It definitely can’t, at least, with its default functionality. So here we are going to see how we can use the existing checks as well as add our own rules for validation of WordPress themes.

/>

Importance of Theme Check Plugin

Theme Check comes up with around 40 built-in tests to validate your theme on both the front-end and admin dashboard. Basically those checks will contain necessary validations for avoiding security concerns and matching theme functionalities against theme development guidelines.

As theme developers or users of third party themes, we should be using such a tool to make sure our themes are up to standards.

The major importance of theme checker comes with its ability to change existing behavior or add new behavior through pluggable plugins. Throughout this article we will be looking at its architecture and the possibilities of extending the plugin to use it as a fully featured theme checking library.

/>

How to Use Theme Check

I assume that most of you have already used this plugin in your WordPress developement tasks. Those who are new to this plugin can grab a copy from the WordPress plugin repository at http://wordpress.org/extend/plugins/theme-check/.

Once installed and activated, you will get a sub menu called Theme Check under the Appearance menu. There you can find a dropdown box containing all the available themes on your WordPress installation. You can select a theme and click the Check it button to start the theme validation. Once the process is completed, you will get a screen like the following.

Screenshot-195 />

Make sure to enable the WP_DEBUG option in the wp-config.php file to TRUE before you start validating themes.

Theme Check results screen will contain all types of errors found in your theme in different error types such as RECOMMENDED, REQUIRED, WARNING, etc. Keep in mind that all these validations are done based on the WordPress theme review standards.

The actual power of Theme Check comes when we extend the plugin with custom validation checks. So let’s dig into the code to find out how it works and how we can extend it with our own checks.

/>

Understanding Theme Check Interface

Theme Check offers a well defined and simple interface for creating checks. All the existing checks as well as new checks need to implemented in this interface to make things work. The following code contained in the checkbase.php file shows the common interface for theme checks.

// interface that all checks should implement

interface themecheck 

	// should return true for good/okay/acceptable, false for bad/not-okay/unacceptable

	public function check( $php_files, $css_files, $other_files );

	// should return an array of strings explaining any problems found

	public function getError();


Basically it contains two functions for checking the theme and providing errors. All the file contents of your theme will be compressed into three main variables as strings. Those variables are then passed into the check function of each check class by the plugin.

Inside the check function we have to implement the validations, and return errors if the check completes as a failure. Then the getError function will be called to add the error messages into the Theme Check results page.

/>

Introduction to Theme Check Process

I think it’s important to understand the initialization process of Theme Check in order to find out how it works and the important sections we need to focus, before extending the plugin functionality.

Once we select the theme and click the ‘Check it’ button, plugin will search for all the files in the selected theme using the PHP RecursiveDirectoryIterator and assigns the whole content of those files into a string variable.

Then the file contents will be separated into three variables, one each for PHP files, CSS files and other files. Then it starts the process of running theme checks, which will be the most important part for us as developers.

Consider the following code for the initial execution process after loading the file variables.

// load all the checks in the checks directory

$dir = 'checks';

foreach (glob(dirname(__FILE__). "/$dir/*.php") as $file) 

	include $file;



do_action( 'themecheck_checks_loaded' );

function run_themechecks( $php, $css, $other ) 

	global $themechecks;

	$pass = true;

	foreach ( $themechecks as $check ) 

		if ( $check instanceof themecheck ) 

			$pass = $pass & $check->check( $php, $css, $other );

		

	}

	return $pass;

}

Code Explanation

  • All the theme checks are stored in the checks directory of the plugin and each of them is included by searching for the PHP files in the directory.
  • Once all the theme checks are loaded, the plugin executes a custom action called themecheck_checks_loaded. This action acts as the most important part in the extending process.
  • Then the system starts to execute theme checks through the run_themechecks function, which takes PHP files, CSS files and other files as variables.
  • Finally the check function of each of the theme checks is loaded into the global $themechecks variable which will be executed to complete the checking process.
/>

Customizing Existing Theme Checks

Most of the theme checks are based on matching regular expressions or matching specific positions in strings. Our first requirement is to figure out how we can modify the behavior of existing checks. So let’s take a look at the IncludeCheck class, which validates how files should be included into a theme.

class IncludeCheck implements themecheck 

	protected $error = array();

	function check( $php_files, $css_files, $other_files ) 

		$ret = true;

		$checks = array( '/(?error; 

}

$themechecks[] = new IncludeCheck;

Code Explanation

  • All theme checks have a protected array for storing errors.
  • Inside the check function, we can include any number of checks in an array. Here we are only having one check.
  • Most of the theme checks will be executed by matching regular expressions and hence the keys for the array of checks will be regular expressions. The value of the respective key should contain the error message to be displayed in the case of failures.
  • Then we have to choose a specific type of file and traverse through each check in the array while updating the global checkcount variable.
  • Next we conduct the regular expression match and assign the errors to global error array on failures.
  • Afterwards we return the status of the check as a success or a failure. Depending on the status, the plugin will grab the necessary errors to be displayed on the results page.
  • Finally we initialize the object of the theme check class and assign it to the global $themechecks array at the end of the file.

Assume that you want to improve an existing theme check by adding new rules or modifying existing rules. All you have to do is add a new item or change the regular expressions of existing items in the checks array.

Now you should have a clear understanding of how theme checks work and how the errors are generated on failures. Let’s move onto the most important part of creating our own custom checks without effecting the core plugin.

/>

Extending Theme Check With Pluggable Plugin

Building new theme checks can be as simple as implementing the interface with a new theme check class and putting the files inside the checks directory of the plugin. But changing the core functionality is not a recommended method as you will always lose your files on plugin updates.

Best practice is to extend plugins using possible options without affecting the core code. Developers of Theme Check have enabled the option of extending functionality using an action hook called themecheck_checks_loaded.

This action hook will be executed after all the theme checks are loaded. Therefore we will have access to the global theme check variable inside pluggable plugins. Now its time to get started by creating a custom plugin.

/>

Removing Existing Checks

Sometimes we might need to disable some theme checks in order to match the requirements of our own themes. You have to either remove the file or comment the initialization code in order to disable them in a normal scenario. But with the power of a pluggable plugin, we can enable or disable them at any time without affecting the core. Let’s see how we can disable theme checks using a plugin.

function custom_themecheck_checks_loaded() 

	global $themechecks;

	$checks_to_disable = array( "Deprecated", "Screenshot_Checks" );

	foreach ( $themechecks as $keyindex => $check ) 

		if ( $check instanceof themecheck ) 

			$check_class = get_class( $check );

			if ( in_array( $check_class, $checks_to_disable ) ) 

				unset( $themechecks[$keyindex] );

			

		}

	}

}

add_action( 'themecheck_checks_loaded', 'custom_themecheck_checks_loaded' );

We can implement the themecheck_checks_loaded action of the Theme Check plugin, inside our own plugins. There we have access to all the loaded theme checks. We can define an array to contain the class names of theme checks we want to disable. Finally we unset the checks contained in the disabled array and theme check will be executed without these validations.

We are allowed to easily modify the existing theme checks using our own plugin. Implementing a theme check from scratch is the main intention of this tutorial. So let’s see how we can create a new theme check.

/>

Creating New Theme Checks

There can be hundreds of scenarios for implementing custom theme checks. Validating custom action hooks is one of my favorite and I’ll be using the code for explanations.

Basically I would like to have certain custom action hooks in my themes to add new functionality. The Thematic theme is a good example for effective usage of custom action hooks in themes. Let’s get started on implementing a custom theme check.

Inside the custom plugin folder, create a new PHP class and implement the interface with the details discussed in the previous sections. The easiest way is to copy an existing theme check and change the check function and initialization. Consider the following code for the implementation of checking custom action hooks.

error[] = sprintf( __( 'REQUIRED: Could not find %1$s. %2$s', 'themecheck' ), $key, $check );

				$ret = false;

			}

		}

		return $ret;

	}

	function getError()  return $this->error; 

}

$themechecks[] = new CustomActions;
?>

In this custom check, I have included regular expressions to validate two custom action hooks called sample_action1 and sample_action2. After a match is found we define a user friendly key to be displayed to the user instead of the original regular expressions. If you compare it with existing checks, you will notice that regular expressions and messages of the check function are the only things which have been modified.

Finally we can add new checks using another implementation of the action as shown in the following code.

function custom_new_themecheck_loadeder() 

	global $themechecks;

	include_once 'custom_actions.php';



add_action( 'themecheck_checks_loaded', 'custom_new_themecheck_loadeder' );

Now you can integrate your own theme checks into the Theme Check plugin.

/>

When to Use Theme Check

Theme Check is developed to validate themes against the WordPress theme development guidelines. Hence it will focus mainly on security concerns and keeping consistent format and features.

We can use this plugin from a different perspective to add features as shown in the last section. If you are an expert in regular expressions, it is possible to create some advanced theme checking with this amazing tool.

It’s up to you to decide when to use custom theme checks. Of course, this is more important for theme developers rather than users of WordPress themes.

I can think of two major scenarios where custom theme checks can become useful.

Maintaining a Basic Framework

I don’t think any developer will develop each WordPress theme from scratch. Most often developers keep their own basic theme framework and build various designs on top of that.

So custom theme checks will be quite useful to keep the consistency of a basic framework across all themes. You can validate things like image formats, sizes, shortcodes, actions etc. inside your own framework.

Developing Themes Beyond Blogs

Generally most WordPress themes are designed to suit a blogging type of theme. WordPress offers built-in action hooks for blog features and hence we won’t have any difficulties extending them.

However, there can be scenarios where you develop themes for applications such as job posting sites, shopping carts, event management systems etc. Those themes have completely different sections and features compared to blogs. WordPress doesn’t offer built-in features for such themes. Hence it would be a good idea to implement action hooks inside such themes and validate them using Theme Check.

/>

Conclusion

I hope you learned the importance of Theme Check and how we can use it to keep consistency across our themes.

I would like to know whether you have used this plugin and what kind of custom theme checks you have implemented to extend its features.

Feel free to share your suggestions and questions in the comments section below.

Original from: http://feedproxy.google.com/~r/Wptuts/~3/CpMOvVx6pgk/

Building a Countdown Timer Widget

April 2nd, 2013 Comments off

We all love a celebration, and now that Easter is over, we look forward to the next occasion. How far away is the next occasion you like to celebrate? Whatever it might be, let’s build a widget plugin to add a countdown timer to our sidebar showing how long we have left to wait.

/>

1. Getting a Head Start

There are a number of things we need to do every time we’re developing a WordPress plugin, and even more specifically, a widget. Thanks to one of our authors here at Wptuts+, Tom McFarlin, we can get underway quickly by using the WordPress Widget Boilerplate.

To use the WordPress Widget Boilerplate, download it, unzip it, and move the directory widget-boilerplate into your /wp-content/plugins/ directory. Then rename it wptuts-countdowner.

Inside that directory you’ll find the main PHP file, plugin.php, which we’ll also rename to wptuts-countdowner.php.

Now we’re ready to get into the code.

/>

2. Re-Badging the Boilerplate

Inside the wptuts-countdowner.php file is all the heavy lifting done for us by the boilerplate. To begin with, we just need to customise it to reflect the name of our plugin. Then once we’ve written our own code, we can also ditch the extra bits of the boilerplate that we may not need.

The plugin header information will look like this:


So fix that up with the details of our plugin:


We’ll also need to change a few references throughout the boilerplate code to change the generic references to use our plugin name. Most of the places where you’ll need to do this are indicated with a ‘TODO‘.

Find and replace ‘widget-name‘ with ‘wptuts-countdowner‘, and also ‘Widget_name‘ with ‘Wptuts_Countdowner‘. Now the plugin has its own name!

Now you have a plugin you can activate in your WordPress Dashboard. Once activated, when you look under Appearance -> Widgets, you’ll see the beginnings of our widget:

Figure-01 />

As you can see, it looks pretty generic at the moment. So update the following code:

		// TODO:	update classname and description
		// TODO:	replace 'wptuts-countdowner-locale' to be named more plugin specific. Other instances exist throughout the code, too.
		parent::__construct(
			'wptuts-countdowner-id',
			__( 'Widget Name', 'wptuts-countdowner-locale' ),
			array(
				'classname'		=>	'wptuts-countdowner-class',
				'description'	=>	__( 'Short description of the widget goes here.', 'wptuts-countdowner-locale' )
			)
		);

To reflect the name and description of our widget:

		// TODO:	update classname and description
		// TODO:	replace 'wptuts-countdowner-locale' to be named more plugin specific. Other instances exist throughout the code, too.
		parent::__construct(
			'wptuts-countdowner-id',
			__( 'Wptuts+ Countdowner', 'wptuts-countdowner-locale' ),
			array(
				'classname'		=>	'wptuts-countdowner-class',
				'description'	=>	__( "A widget to display a countdown timer in your site's sidebar.", 'wptuts-countdowner-locale' )
			)
		);

Now we have this:

Figure-02 />
/>

3. Collect Info From the User

Our widget is going to need a name and date for the event to count down (or up) to.

So, we need to create a form to be used when our widget is added to a sidebar for configuration. The WordPress Widget Boilerplate separates the HTML portion into view files for a nice, clean separation of concerns. We’ll setup our variables in the method, and then the form itself in the admin view.

Here’s the method. Changes for our plugin indicated with highlights.

	/**
	 * Generates the administration form for the widget.
	 *
	 * @param	array	instance	The array of keys and values for the widget.
	 */
	public function form( $instance ) 
	
    	// TODO:	Define default values for your variables
		$instance = wp_parse_args(
			(array) $instance
		);
	
		// TODO:	Store the values of the widget in their own variable
		if ( ! empty( $instance['event'] ) ) 
			$event = $instance['event'];
		
		else 
			$event = __( 'Event Name', 'wptuts-countdowner-locale' );
		

		if ( ! empty( $instance['event_date'] ) ) 
			$event_date = $instance['event_date'];
		
		else 
			$event_date = date( 'Y-m-d' );
		
		
		// Display the admin form
		include( plugin_dir_path(__FILE__) . '/views/admin.php' );	
		
	} // end form

You’ll note at the end of the method, there’s an include for the view. So open up /wp-content/plugins/wptuts-countdowner/views/admin.php. Add the following code into that file:

Now you can refresh the WordPress Dashboard and add the widget to your sidebar, which will look like this:

Figure-03 />

Sadly, whatever you put in those fields won’t save yet, so we need to modify the update method as follows:

	/**
	 * Processes the widget's options to be saved.
	 *
	 * @param	array	new_instance	The previous instance of values before the update.
	 * @param	array	old_instance	The new instance of values to be generated via the update.
	 */
	public function update( $new_instance, $old_instance ) 
	
		$instance = $old_instance;
		
		// TODO:	Here is where you update your widget's old values with the new, incoming values
		$instance['event'] = strip_tags( $new_instance['event'] );
		$instance['event_date'] = strip_tags( $new_instance['event_date'] );
    
		return $instance;
		
	 // end widget

Now we have a working widget admin! You can drag the widget into your sidebar, and save the details for an event, like Christmas:

Figure-04 />
/>

4. Showing on the Front End

Now we have event details for the countdown time, let’s show it on the front end of the site in the sidebar.

	/**
	 * Outputs the content of the widget.
	 *
	 * @param	array	args		The array of form elements
	 * @param	array	instance	The current instance of the widget
	 */
	public function widget( $args, $instance ) 
	
		extract( $args, EXTR_SKIP );

		echo $before_widget;
    
		// TODO:	Here is where you manipulate your widget's values based on their input fields

		$event = apply_filters( 'wptuts_countdowner_event', $instance['event'] );
		$event_date = apply_filters( 'wptuts_countdowner_event_date', $instance['event_date'] );
    
		include( plugin_dir_path( __FILE__ ) . '/views/widget.php' );
		
		echo $after_widget;
		
	 // end widget

As with the admin form, we’re using a view for the front end too, to keep the HTML separate. Open up your /wp-content/plugins/wptuts-countdowner/views/widget.php file, and add the following:



/>

5. Counting Days

So we have an event and a date / time displaying now, but that doesn’t give us a countdown. We need to add a little bit of code in to determine how many days between our event’s date, and today’s date. Because our date could be in the past or the future, we’ll also need to add a suffix word to indicate which.

Here’s the code we add to the front end part of the widget:

	/**
	 * Outputs the content of the widget.
	 *
	 * @param	array	args		The array of form elements
	 * @param	array	instance	The current instance of the widget
	 */
	public function widget( $args, $instance ) 
	
		extract( $args, EXTR_SKIP );

		echo $before_widget;
    
		// TODO:	Here is where you manipulate your widget's values based on their input fields

		$event = apply_filters( 'wptuts_countdowner_event', $instance['event'] );
		$event_date = apply_filters( 'wptuts_countdowner_event_date', $instance['event_date'] );

		$event_date_seconds = date( 'U', strtotime( $event_date ) );
		$today_date_seconds = date( 'U' );

		$event_date = human_time_diff( $event_date_seconds );
		$suffix = ( $event_date_seconds > $today_date_seconds ? 'away' : 'ago' );

		include( plugin_dir_path( __FILE__ ) . '/views/widget.php' );
		
		echo $after_widget;

	 // end widget

What we’re doing there is getting the current timestamp in seconds for the event, and for today. We then get the human-readable version (i.e. 267 days). We also work out, based on whether the event date is in the past or the future, which suffix word to use.

Now we have a suffix word, we’d better add it to the view:


Now we have something that looks a bit more respectable and makes a bit more sense.

Figure-05 />
/>

6. Pick a Date

It’s a little ugly to have to manually type in a date, so let’s add in the jQuery UI Datepicker, seeing as it’s included in WordPress.

One thing that isn’t included though, is the CSS for the date picker. So grab the CSS file and images directory from Helen Hou-Sandi’s WP Admin jQuery UI repository on GitHub, and put them into your /wp-content/plugins/wptuts-countdowner/css/ directory.

Then we need to get WordPress to load them by modifying the boilerplate’s register_admin_scripts and register_admin_styles methods, like so:

register_admin_scripts

	/**
	 * Registers and enqueues admin-specific JavaScript.
	 */	
	public function register_admin_scripts() 

		wp_enqueue_script( 'jquery-ui-datepicker' );	
		// TODO:	Change 'wptuts-countdowner' to the name of your plugin
		wp_enqueue_script( 'wptuts-countdowner-admin-script', plugins_url( 'wptuts-countdowner/js/admin.js' ) );
		
	 // end register_admin_scripts

register_admin_styles

	/**
	 * Registers and enqueues admin-specific styles.
	 */
	public function register_admin_styles() 
	
		// TODO:	Change 'wptuts-countdowner' to the name of your plugin
		wp_enqueue_style( 'wp-admin-jquery-ui', plugins_url( 'wptuts-countdowner/css/jquery-ui-fresh.css' ) );
		wp_enqueue_style( 'wptuts-countdowner-admin-styles', plugins_url( 'wptuts-countdowner/css/admin.css' ) );
	
	 // end register_admin_styles

Finally, add your jQuery code into the boilerplate’s admin.js file to hook the datepicker up to the field.

(function ($) 
	"use strict";
	$(function () 
		// Place your administration-specific JavaScript here
		jQuery('.wptuts-event-date').datepicker(
			dateFormat : 'yy-mm-dd'
		);
	});
}(jQuery));
/>

7. Cleaning Up

The boilerplate contains a few things we haven’t used in this plugin, so it’d be a good idea to lighten the load and remove them. The extras are these files:

  • /css/admin.css
  • /css/widget.css
  • /js/widget.js

And these methods in the wptuts-countdowner.php file:

  • activate
  • deactivate
  • register_widget_scripts
  • register_widget_styles
  • Also line wp_enqueue_style( 'wptuts-countdowner-admin-styles', plugins_url( 'wptuts-countdowner/css/admin.css' ) ); from the register_admin_styles method
/>

Conclusion

There you have it! A WordPress plugin based on the Widget Boilerplate that lets you show how many days until (or since) an event.

I hope you found it useful, please share your thoughts in the comments below.

Original from: http://feedproxy.google.com/~r/Wptuts/~3/6rbsa4FpcJ8/

Creating an Image-Based Archive Page: Styling

March 29th, 2013 Comments off

This entry is part 2 of 2 in the series Creating an Image-Based Archive Page

In Part 1 of this tutorial you learned how to create a template file for a custom post type in order to display featured images and titles for each post. You registered a custom post type of ‘animal’ and created a file called archive-animal.php to display an archive of animals.

In this tutorial you’ll learn the CSS required to add a grid layout to the images and overlay post titles over the images. You’ll then learn how to add a hover effect, so the name of the animal only appears when the user hovers their mouse over each image.

/>

Resources You’ll Need for This Tutorial

This tutorial uses a child theme with the Twenty Twelve theme as its parent. You’ll need a WordPress installation set up with this theme installed (it should be installed as the default). If you’re unsure of how to set up a child theme, see the instructions on the WordPress Codex.

You’ll also need a code editor with FTP access to your site, unless you’re developing locally in which case you won’t need FTP.

You’ll need the child theme created in Part 1 of this tutorial, with the archive-animal.php template file.

You can download the code bundle, including the child theme files, using the Download link above.

/>

The Archive Page

The archive page you’re starting with displays the image and title of each post as shown in the screenshot. In this part of the tutorial you don’t need to edit the archive page at all, just the stylesheet for the theme.

The starting archive page without styling
/>

Adding the Grid Layout

To lay the images out in a grid you’ll need to use floats. Open your theme’s stylesheet and add the following:

.post-type-archive-animal article.entry-content 
	position: relative;
	float: left;
	clear: none;
	margin: 10px;

This CSS targets the animals archive by using .post-type-archive-animal, a class which WordPress applies to the body element because the Twenty Twelve theme uses the body_class() function to assign classes to this element.

It removes any clear settings for the article element and adds a float and a margin for layout.

You will now have your post listings in a grid:

The archive page with a grid layout
/>

Overlaying the Text and Adding Opacity

The next step is to position the title of each post so that it’s overlaid over the image, and add a semi-opaque background to improve legibility.

Below the CSS you’ve already added, add the following:

/* styling to add image overlay and opaque background */
.post-type-archive-animal .entry-content img 
	position: relative;
	overflow: hidden;
	background: transparent;
	float: left;


.post-type-archive-animal .archive-title 
	position: absolute;
	text-align: center;
	left: 0;
	bottom: 0;
	width: 140px;
	height: 70px;
	background: rgba(255, 255, 255, 0.5);
	padding: 50px 5px 30px 5px;
	filter: alpha(opacity=50);

This does a few things. Firstly, on the .entry-content img element it adds position: relative so that absolute positioning will work for the .archive-title element contained within it, as well as adding a float which ensures the layout works correctly.

Next, for the .archive-title element it adds absolute positioning and sets that up using the left and right values. It adds width, height and padding which add up to 150px by 150px, the size of the thumbnail images in this theme. Finally it adds a semi-opaque background using rgba, with a fallback for IE using filter: alpha(opacity=50).

The images now have the text overlaid with a semi-opaque background:

Titles are now overlaid over images with a semi-opaque background
/>

Adding the Hover Effect

You may decide that you’re happy with the archive page as it is. In some cases it’s preferable for the titles to be constantly visible. But if you want the images to have greater priority and be visible without text or a background obscuring them when the page first loads, you can add a hover effect, hiding the text until the user hovers the mouse over an image.

To do this, you’ll need to edit the styling for the .archive-title class and add some extra styling for the :hover state as follows:

/* styling to add the hover effect */
.post-type-archive-animal .archive-title 
	position: absolute;
	text-align: center;
	left: 0;
	bottom: 0;
	width: 140px;
	height: 70px;
	opacity: 0;
	padding: 50px 5px 30px 5px;


.post-type-archive-animal .archive-title:hover,
.post-type-archive-animal .archive-title a:hover  
	display: block;
	background: rgba(255, 255, 255, 0.5);
	-moz-opacity: 0.7;
	filter: alpha(opacity=50);
	opacity: 1;

This provides a slightly different version of the styling for the .archive-title element, with opacity set to 0. The positioning, padding and width are exactly the same as you added earlier for the overlay effect.

It then targets the title and links within it in the hover state, and adds a background and opacity to these. These settings are similar to those you added earlier when adding a semi-opaque background to the titles, but now that background (and the title itself) only appears when the user hovers the mouse over an image.

When the archive page is first loaded, the images appear without any text overlaid:

Text is invisible when the page is loaded

When the user hovers their mouse over one of those images, the title will appear:

When the user hovers over an image, the text appears

You now have a nice archive page using a grid of images with a hover effect for text.

/>

Summary

In these two tutorials, you’ve learned how to do the following:

  • Register a custom post type and create a custom archive page to display posts form that post type
  • Create a custom loop to display a featured image and title for each post on the archive page
  • Use CSS to lay the images out in a grid
  • Add an overlay effect for the title of each post so it’s overlaid on top of the featured image
  • Finally, add a hover effect so that the text is invisible until the user hovers over an image

The code required to do this is relatively straightforward and compatible with major browsers, including older versions of IE.

/>

Useful Resources

Codex pages:

Tutorials:

CSS Resources:

Original from: http://feedproxy.google.com/~r/Wptuts/~3/D7rJAzvd5aY/

AutoBlogged