Archive

Posts Tagged ‘widgets’

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/

Introduction to WordPress Plugin Development: Early Bird Tickets Now Available!

May 9th, 2013 Comments off

Today, we are excited to announce a fantastic new workshop led by Instructor Tom McFarlin: Introduction to WordPress Plugin Development

Are you an aspiring WordPress developer? Are you ready to take the next step and start building your own custom plugins for WordPress? Our newest Tuts+ Live Workshop is the perfect way to get started!

Early Bird tickets are half-price at only $49, but places are strictly limited so act fast to make sure you don’t miss out! />

/>

Introduction to WordPress Plugin Development

Our newest Tuts+ Live Workshop, Introduction to WordPress Plugin Development, teaches you everything that you need to know to start developing WordPress plugins; from setting up a local development environment, all the way through to building a WordPress plugin that’s ready for release into the WordPress Plugin Repository.

It’s led by Instructor Tom McFarlin, a self-employed WordPress developer who divides his time between running his own WordPress development shop, building plugins for WordPress, blogging every day about software development in the context of WordPress, and working for 8BIT (the team responsible for Standard Theme and WP Daily).

Each weekly workshop will last one hour, running over a five week period. You’ll have the opportunity to follow along with Tom, ask questions live during the workshop, and complete a weekly homework assignment. Not able to make it to the live recording? No problem! All of the workshop recordings will be made available online the day after the live workshop.

Learn more about Introduction to WordPress Plugin Development

/>

Grab an Early Bird Ticket Now!

We’re offering a special Early Bird price of $49, but these tickets are limited. Once the Early Bird tickets have disappeared, the workshop will be $99.

If you’re interested in future workshops then definitely join the Tuts+ Live Workshops mailing list to stay posted on upcoming workshops and get notified as soon as they’re available, the Early Bird tickets for our previous workshops have all sold out, so it’s worth getting ahead of the game!

We’re really excited about new workshop, Introduction to WordPress Plugin Development, but places are strictly limited so act fast to make sure you don’t miss out!

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

Try Tuts+ Premium, Get Cash Back!

May 8th, 2013 Comments off

Try Tuts+ Premium and get cash back on a monthly subscription.

At $19 a month, Tuts+ Premium is fantastic value. But it’s even better when we hand your first $19 right back to you! For a limited time, we’re offering $19 cash back to new Tuts+ Premium monthly subscribers when signing up via PayPal.

If you’ve been thinking about checking out our extensive library of courses, tutorials, eBooks and guides, there’s never been a better time to join up and dive in.

But this offer ends at noon on the 20th of May AEST, so act fast.

Become a Tuts+ Premium Member to take your creative and technical skills to a new level. />

/> What can you learn on Tuts+ Premium? Glad you asked! Currently, more than 15,000 members are sharpening their skills in a wide range of areas including web design, web development, Photoshop, vectors, video effects, and many more.

With Tuts+ Premium you learn from expert instructors in every field, such as:

  • Designer Justin Maller (Nike, Verizon, DC Shoe Co.)
  • Illustrator Russell Tate (McDonald’s, Coca-Cola)
  • Developer Burak Guzel (Software Engineer at Facebook)

Join now and get instant access to your very own library of courses, tutorials, and eBooks, available whenever you need them. Become part of a community of over 15,000 members and start getting better at the skills you care about. Our dedicated team adds new content weekly, so there’s always something fresh to sink your teeth into.

Join Tuts+ Premium

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

A Walkthrough for Jetpack’s “Post by Email” Feature

May 6th, 2013 Comments off

WordPress has a sufficient, mostly responsive, back-end and great applications for mobile devices, but there might come a day when you’ll just want to send an email to post an entry to your website.

In this post, we’re going to go through this handy little feature of Jetpack: Post by Email.

WordPress has a Post via Email functionality in its core, but it’s far from being handy or user friendly.

As the Codex says, you have to:

  1. Create a dedicated e-mail account to be used solely for posting to your blog
  2. Configure WordPress to access that account via POP3
  3. Configure WordPress to publish messages from that e-mail account

And even if you do, you’re stuck with plain text posts and you can’t post any email attachments!

Plus, you have to at least set up a function in your theme (or as a separate plugin) for WordPress to recognize your email as a post. Oh, did I mention that you can only select one category to post and you can’t set any tags or any other kind of taxonomy?

Luckily, this problematic approach can be replaced with Jetpack, another creation from Automattic. The Post by Email module solves all the problems above and allows you to do lots more. In short, you can:

  • Use HTML in your email
  • Include attachments (and include the attached images as a slideshow or an inline gallery)
  • Set a title (and a slug) different than your email title
  • Set categories and tags
  • Turn on or off comments for the post
  • Set an excerpt
  • Change the status of the post
  • Set a password for the post
  • Set a time for the post to be published
  • Add <--more--> and <--nextpage--> tags inside the post
  • End your post anywhere inside your email
  • Include a PollDaddy poll
  • Turn off geotagging
  • Set Publicize options, another module of Jetpack
/>

Warming Up

You need to do a bunch of things with Jetpack, too:

  • Install the plugin
  • Connect your website with your WordPress.com account
  • Check if the “Post by Email” module is enabled
  • Go to Users » Your Profile and click on “Enable Post by Email”
  • Get the special email address and add it to your address book

Notice that you don’t even have to use your keyboard while taking these steps – except, maybe, entering your WordPress.com credentials. After doing these in order, you’re ready to send your first post via email!

/>

Available Shortcodes

Now that you’re all set on your WordPress admin panel, you can now log in to your email account – the one you’re registered with WordPress.com. With your first post (and all others, naturally), you can use the following shortcodes anywhere inside your email:

Title: [title Hello World!]

Parameters: The specified title.

If you want to send an email with a different title than the title of the post, you can use this shortcode to set a title for the post. If this shortcode is used, Jetpack will disregard the title of the email.

Slug: [slug oh-hai]

Parameters: The specified slug.

The usual “slug”, the words on the address bar. You can use this shortcode to use shorter URLS like myblog.com/hawaii-trip/ and avoid huge ones like myblog.com/a-trip-to-hawaii-what-i-expected-to-see-and-what-i-saw/.

Categories: [category News, Personal]

Parameters: Comma separated category names or IDs.

You can set any category you want with this shortcode. Just use names or IDs as parameters and you’re good to go! It even gets the right category when you don’t use the full name, like “Anno” instead of “Announcements”.

Tags: [tags lorem, ipsum, dolor]

Parameters: Comma separated tag names.

Like categories, you can use tag names

P.S. As far as I can see, it doesn’t support custom taxonomies, which is a bummer. It would be great if a [tax] shortcode is introduced and used like this: [tax custom-taxonomy]lorem, ipsum, dolor[/tax] (where the default parameter is “tag”). Let’s hope the module will support this in the future :) .

Comments: [comments off]

Parameters: “on” or “off”.

No need to explain this one: You can turn on or off comments on your post with this shortcode.

Post Status: [status private]

Parameters: “publish” (default), “private”, “pending” or “draft”.

Again, this is self-explanatory: You can set the four parameters to set the status of your post.

Post Password: [password CorrectHorseBatteryStaple]

Parameters: The specified password.

You can protect your post with a password with this shortcode.

P.S. I got the password from an XKCD comic.

Publish Date/Time: [delay +2 days]

Parameters: a date/time description like “+1 week 2 days 3 hours” or “next Saturday” or “25 November 2013″.

Using the strtotime format, you can set the date and time of your post. If you set the parameter to “+2 hours”, your post will be published 2 hours after you send the email.

Excerpt: [excerpt]...[/excerpt]

If you’re using the “excerpts” of WordPress posts on your website, you can set an excerpt between [excerpt] and [/excerpt] tags.

Geotagging: [geotag off]

Parameters: “on” or “off”.

If your phone (or email client) is using your GPS information inside the emails, geotagging will be enabled by default. If you don’t want to share that information on your posts, you should disable it by using this shortcode with the parameter “off”.

Publicize: [publicize facebook twitter]

Parameters: Space separated list of services (like Facebook and Twitter) or “off”.

Jetpack has another useful module called Publicize, letting you share your post automatically on social networks when it’s published. If you want to do the same with email, you can use this shortcode to Publicize your post.

Separating Content: [more] and [nextpage]

These two are also self-explanatory: If you ever need to use the <--more--> or <--nextpage--> tags inside your post, you can use these shortcodes.

Attachments: [slideshow] and [noslider]

By default, Jetpack will include your image attachments in the post. If you attach just one image, it will be displayed inline and if you attach more, all of them will form a gallery.

If you don’t like this behavior, you can use [nogallery] to display all images inline or use [slideshow] to replace the gallery with a slideshow.

PollDaddy Polls: [poll]

Parameters: “type” (single, multi or a number), “style” (manga or medium), “other” (yes or no).

If you have a PollDaddy account, you can use this shortcode to include a poll inside your post. Here’s an example on how to use it:

[poll type="3" style="medium" other="yes"]
What are your favorite Tuts+ blogs? (select three)
* Wptuts+
* Nettuts+
* Webdesigntuts+
* Psdtuts+
* Phototuts+
[/poll]

The End: [end]

There could be email signatures you can’t remove (company policy, hmpfh) or your smartphone could add lines like “sent from myPhone” (that company‘s policy, hmpfh) and you wouldn’t want these signatures to be included in your post.

Jetpack automatically cuts out the text after a signature block or an


tag, but you can use [end] alternatively to end the post right where you use it.

/>

Wrapping Up

I always thought that the core “post via email” feature of WordPress was too much limiting, kind of redundant and absolutely hard to use. Now that we went through everything Jetpack’s “Post by Email” module can do, I’m glad that there’s an alternative to it, also developed by Automattic.

What do you think about this feature – do you plan to use it? Share your comments below and don’t forget to share the post!

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

Quick Tip: After the Content – Disclaimer

April 29th, 2013 Comments off

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

Does your content get scraped by others? Do people without common sense post your content without attribution? Maybe that’s because you -kind of- let them.

In this post, we’re going to see why and how should you include a little “disclaimer” in your posts.

/>

“Disclaimer” to Warn or Inform Nicely

There are still some people left who think that “borrowing” a post without attribution is OK. Believe it or not, displaying a disclaimer is actually effective for them … if their intentions are good.

If you’re going to put a disclaimer under the post, it’s better to leave a friendly note instead of a dark warning. People tend to react to warm messages instead of cold “notices.”

Something like this would suffice:

Thanks for reading the article! If you enjoyed it and want to post it somewhere else, it would be pretty cool if you also shared the link of this page as a reference. Thanks in advance for your kindness!

You could add this right after the content, or after other elements like the author info box or the “Share This” section – as long as it’s noticable, it’s fine.

Tip: You can also use it outside The Loop because we didn’t use the the_permalink() function and used echo get_permalink( $post->ID ) instead.

As I said, if the person who wants to “borrow” your post is right minded, they wouldn’t mind placing a link under (or above) the content to attribute to you, when they see this kind note. Plus, it kind of looks more professional (if you consider it important to look that way).

For the ill minded, unfortunately, we can’t do much. That said, we can trick them to include a reference to our website automatically. Check out WPBeginner’s post: “How To Add a Read More Link to Copied Text in WordPress

/>

Conclusion

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

Do you think we can do more with this section? Please comment and share your ideas!

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

Quick Tip: After the Content – Author Info

April 24th, 2013 Comments off

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

Unless you’re hiding your identity on purpose and your readers know it, they will always be wondering about the author of the content you serve. Not just the name – they will care about who you are and where they can reach you.

In this post, we’re going to learn the importance of the “Author Info” section.

/>

“Author Info” to Introduce the Intelligence

“This a brilliant / terrible post! I wonder who wrote this…”

This is what people think when they read a great article (or an awful one). As long as the content isn’t boring, your audience would very much like to get to know about you or your authors.

It doesn’t matter if you’re blogging solo or together with other authors: You should promote yourself! I can’t tell you how I felt when I realized that I missed the chance to offer my short biography to my audience … for seven years of blogging!

For the sake of minimalism, I always chose not to display a little picture of me with some useful information like my social media accounts or even a simple sentence about who I am, with a link to my “About” page. Don’t make the mistake I did and put an Author Box under your posts today!

/>

Displaying an “Author Info” Vox

I could put together some lines of code or introduce a plugin, but Will Wilson recently wrote a fantastic article about building a custom “Author Info” box.

Check it out:

“On sites like Wptuts+ you get to read articles from a massive team of writers and bloggers, we all have our own writing style and personalities. Like Wptuts+, on most multi-author sites, you will find a nice little author information box somewhere on the page. Today I’m going to show you how you can create one for your very own site.”

Read More: Show Yourself Off With a Custom Author Box

The article is suitable for both multi-author and single-author blogs and it’s a terrific example of how an “author info” section should be included.

/>

Conclusion

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

Can you think of anything that could extend the “author info” section? Please share your thoughts with us!

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

Plugin Templating within WordPress

April 22nd, 2013 Comments off

When it comes to creating a Custom Post Type within a WordPress plugin, there’s always the same problem: you need to create a custom single-[cpt_slug].php file in your theme folder if you don’t want to use the default single.php file from your theme.

In this post I’d like to cover two aspects of using custom templates. The first step is to show that we can use a custom file contained directly in the plugin itself instead of loading the default single.php, and the second one is how to create your own custom file in your theme folder.

Many plugins like Easy Digital Downloads or Shopp, use this method: the plugin checks if you define a custom template in your theme folder, if it is the case then the file is loaded, otherwise the default plugin template file is loaded. In both cases the theme default single.php file isn’t loaded.

/>

Define the Plugin and Its Structure

The very first step is to create a plugin, let’s call it “Template Chooser“. Create a “template-chooser” folder under /wp-content/plugins/, with the following structure:

template_chooser_structureThe plugin structure

Then open the main file template-choose.php and place the following plugin header code:

/*
Plugin Name: CPT template Chooser
Plugin URL: http://wp.tutsplus.com/
Description: Loads a custom template file instead of the default single.php
Version: 0.1
Author: Remi Corson
Author URI: http://wp.tutsplus.com/
*/
/>

Define the Plugin Constants

Later in the plugin we will need to easily retrieve the plugin URL and its path, that’s why we need to define a few constants:

/*
|--------------------------------------------------------------------------
| CONSTANTS
|--------------------------------------------------------------------------
*/

if ( ! defined( 'RC_TC_BASE_FILE' ) )
	define( 'RC_TC_BASE_FILE', __FILE__ );
if ( ! defined( 'RC_TC_BASE_DIR' ) )
	define( 'RC_TC_BASE_DIR', dirname( RC_TC_BASE_FILE ) );
if ( ! defined( 'RC_TC_PLUGIN_URL' ) )
	define( 'RC_TC_PLUGIN_URL', plugin_dir_url( __FILE__ ) );
/>

Register a Custom Post Type

To go further, we have to setup a new custom post type, let’s create a “Testimonial” CPT, with some very basic supports and features. As the aim of the post is not to teach how to create a custom post type, I’ll use a pretty simple code divided in 3 parts: the custom post type labels, the supports, and the custom post type arguments. All that embed in a single function:

/*
|--------------------------------------------------------------------------
| DEFINE THE CUSTOM POST TYPE
|--------------------------------------------------------------------------
*/

/**
 * Setup testimonial Custom Post Type
 *
 * @since 1.0
*/

function rc_tc_setup_post_types() 

	// Custom Post Type Labels
	$labels = array(
		'name' => esc_html__( 'Testimonials', 'rc_tc' ),
		'singular_name' => esc_html__( 'Testimonial', 'rc_tc' ),
		'add_new' => esc_html__( 'Add New', 'rc_tc' ),
		'add_new_item' => esc_html__( 'Add New Testimonial', 'rc_tc' ),
		'edit_item' => esc_html__( 'Edit Testimonial', 'rc_tc' ),
		'new_item' => esc_html__( 'New Testimonial', 'rc_tc' ),
		'view_item' => esc_html__( 'View Testimonial', 'rc_tc' ),
		'search_items' => esc_html__( 'Search Testimonial', 'rc_tc' ),
		'not_found' => esc_html__( 'No testimonial found', 'rc_tc' ),
		'not_found_in_trash' => esc_html__( 'No testimonial found in trash', 'rc_tc' ),
		'parent_item_colon' => ''
	);

	// Supports
	$supports = array( 'title', 'editor' );

	// Custom Post Type Supports
	$args = array(
		'labels' => $labels,
		'public' => true,
		'publicly_queryable' => true,
		'show_ui' => true,
		'query_var' => true,
		'can_export' => true,
		'rewrite' => array( 'slug' => 'testimonials', 'with_front' => true ),
		'capability_type' => 'post',
		'hierarchical' => false,
		'menu_position' => 25,
		'supports' => $supports,
		'menu_icon' => RC_TC_PLUGIN_URL . '/includes/images/testimonials_icon.png', // you can set your own icon here
	);

	// Finally register the "testimonial" custom post type
	register_post_type( 'testimonial' , $args );


add_action( 'init', 'rc_tc_setup_post_types' );
/>

Do Not Use the Default single.php File

Now that our custom post type is registered, we need to create a function that will tell WordPress not to use the default single.php from the theme.

Because yes by default when displaying a custom post type on the frontend WordPress will check if a file called single-testimonial.php exists and will load it. If not, it will look for the single.php. But we don’t want to use any of them.

We want WordPress to load a custom file from the plugin. To do so, we have to hook a new function to the “template_include” filter. In this function the aim is to check the type of the post and act in consequence:

/*
|--------------------------------------------------------------------------
| FILTERS
|--------------------------------------------------------------------------
*/

add_filter( 'template_include', 'rc_tc_template_chooser');

/*
|--------------------------------------------------------------------------
| PLUGIN FUNCTIONS
|--------------------------------------------------------------------------
*/

/**
 * Returns template file
 *
 * @since 1.0
 */

function rc_tc_template_chooser( $template ) 

	// Post ID
	$post_id = get_the_ID();

	// For all other CPT
	if ( get_post_type( $post_id ) != 'testimonial' ) 
		return $template;
	

	// Else use custom template
	if ( is_single() ) 
		return rc_tc_get_template_hierarchy( 'single' );
	

}
/>

Load the Right Template

As you can see, on line 33 we are calling a new function rc_tc_get_template_hierarchy(). This is the function that will check if WordPress has to load the custom file from the plugin or the template from the theme folder.

Please note that when I’m talking about the “template from the theme folder”, I’m talking about a custom file loaded instead of the single.php.

Let’s say you don’t want to load the template included in the plugin but create your own custom template, all you have to do is to create a new folder in the theme folder, name it “plugin_template” and within this folder create a single.php file. This will be your new default single.php loaded only for testimonials displayed on the frontend.

Are you still with me? Okay, so let’s create the function:

/**
 * Get the custom template if is set
 *
 * @since 1.0
 */

function rc_tc_get_template_hierarchy( $template ) 

	// Get the template slug
	$template_slug = rtrim( $template, '.php' );
	$template = $template_slug . '.php';

	// Check if a custom template exists in the theme folder, if not, load the plugin template file
	if ( $theme_file = locate_template( array( 'plugin_template/' . $template ) ) ) 
		$file = $theme_file;
	
	else 
		$file = RC_TC_BASE_DIR . '/includes/templates/' . $template;
	

	return apply_filters( 'rc_repl_template_' . $template, $file );
}

/*
|--------------------------------------------------------------------------
| FILTERS
|--------------------------------------------------------------------------
*/

add_filter( 'template_include', 'rc_tc_template_chooser' );
/>

The Plugin Default Template

Now create a new testimonial in the administration. Then open includes/templates/single.php and then copy and paste this simple code:



we are in the plugin custom file


If you visualize the testimonial on the frontend you should see the “we are in the plugin custom file”. That’s what we wanted. But if the plugin template file doesn’t fit your needs or if you simply want to create a more personal design, you can create a file in your theme folder.

/>

The Theme Default Template

To create a custom template that does not use the default one from the plugin, you can create a new folder called “plugin_templates” in your theme folder. Create a new file called single.php and place this code:



we are in the theme custom file


/>

Conclusion

So what did we do exactly? Well, we created a plugin that registers a custom post type “Testimonial“. We achieved functionality to load a custom file stored in the plugin folder instead of the default single.php or single-testimonial.php files from the theme folder. We also managed to load a custom file instead from the theme folder located under “plugin_templates“.

Why is this nice? Because when you create your own plugin you can provide a default template to display the custom post type so you’re giving the choice to the final user whether to use their own template or not.

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

Developing Plugins With a Distributed Team

April 16th, 2013 Comments off

Recently, I had the opportunity to build a plugin with two other developers – Pippin Williamson and Andrew Norcross. We came up with the idea via Twitter, scoped it via email, and built it using GitHub using its tools all prior to releasing it.

I know – the title of this post sounds all too familiar especially given the global economy in which we all live today. After all, many of us work from our home offices, coffee shops, or wherever else while the home base of our company is located elsewhere.

But this is a different type of distributed team.

First, let’s acknowledge that when it comes to building software in the WordPress space, we’re extremely fortunate to be able to do so by ourselves, with a couple of friends, or within the context of a team in a corporate environment.

Even though WordPress itself is built by a lot of people all over the world, you don’t often see the same experience being pulled through with themes or plugins. This isn’t to say that it’s never done (because it is), but it appears that it’s done less so.

Now, the purpose of this post is not to promote the aforementioned plugin, but it’s more of a call to action for us to find more creative ways to build publishing products with teams – namely, our “Internet friends” or tweeps – with whom we may not have previously worked.

But there are a few learnings that have come from this process that I think are worth sharing for the sake of helping others get into experimenting with developing projects with fellow tweeps.

/>

Scope Is Key

Simply put, locking in the scope is part of identifying the core features of your plugin. When you first start out, it’s important to be able to succinctly state what your product is going to do.

In our case, we said:

We want to make it easy for people to identify what comments need a reply from the post’s author.

What this does is allow you to define a grid – or a scope – through which all potential features can be filtered. If it doesn’t fit in with the core idea of the plugin, then it’s not fit for the first release.

That said, this feels almost like it’s a bit cliche because it should be expected for any software project: identify the scope, lock it in, and then aim for it.

But when you’re working with a group of friends on a free project, this can become increasingly easy to ignore.

Case in point: As a single developer, how often have you thought to yourself: “That’d be a cool feature to build!” And then, because you had no one to really hold you accountable to build it, you were able to achieve it.

This isn’t to say that’s wrong – it may be, it may not be – I don’t know the specifics of your project; however, if you’re working with a team on a project, taking time to work on something that is outside of the scope is time wasted that can ultimately detract from the core of the plugin. Furthermore, it can hold up your peers’ development time while they wait for your feature to be complete especially if there’s a dependency on your work.

Finally, if you get a group of developers together to build something for the fun of it, the project may never get done because you’ve taken the idea of “wouldn’t this be cool,” and multiplied it by however many are on your team.

The point is that even though you’re running the project with friends, you’ve got to scope the project lean, and scope the project early; otherwise, you’ll never be done.

/>

Delivery Date Matters

And this brings us to the second point: Despite the fact that you have no one “above you” holding you accountable to your delivery date, you still have an obligation to yourselves, your scope, and those who may be waiting for the product to complete development.

Granted, there’s always the argument that can be made that since people aren’t paying, then they have no real demand on when something should be finished; however, if you’ve set a date, there’s a level of integrity that should be matched when aiming to deliver your work.

What’s a plugin that @nocross and I could build during #wcmia and release for free? #WordPress

— Pippinsplugins (@pippinsplugins) February 13, 2013

To that end, it’s important that you set a delivery date – however arbitrary it may be – and then set milestones to make sure the pace of development matches that date.

For example, Pippin, Andrew, and I scoped the plugin in February and aimed to have the plugin completed in April by the end of one of the WordCamp events. Sure, the deadline was somewhat arbitrary, but it kept us honest not only in our own development efforts, but it allowed us to hold one another accountable for our own specific tasks.

This means that if I was dragging my feet, Pippin or Andrew could call me on it (of course, it works all around).

/>

Keep It Open

GitHub Repository

Finally, working with friends is great especially when you’re unified around the same vision. It allows you to get more done faster since the work can be spread across more than a single person.

But the nice thing about software is that it can be open sourced. This means that if others are not only interested in the project, or are bought into the vision, they can even contribute to it.

But here’s the thing, software is inevitably going to breed two things:

  1. Bugs
  2. Feature Requests

Using tools such as GitHub allows the plugin’s user base – be it users, developers, or designers – to voice their issues and/or feature requests in a centralized way.

Furthermore, it allows the core team to not only assign each set of issues to their own milestones, but it allows for other contributors who are also brought into the vision know exactly how they can contribute. There’s no guesswork. There’s no “hey, maybe we could do this!

Instead, there’s a list of issues and requests that are needed (permitting the list is kept up to date) so that contributors know they are ultimately improving the product – not just blindly adding something because they think it would look good.

Of course, this isn’t limited to GitHub: Whatever source control system and ticket system you opt to use, make sure it’s something that makes it easy for others to interact and others to view outstanding issues. The last thing contributors need is yet-another-hurdle for contributing to your project.

/>

Conclusion

So there you have it: Three points to working on products with a distributed team outside of the typical organized environment.

Simply put, make sure that you scope your project, stick to your delivery date, and allow others to contribute who are interested. By doing this, you’re making it easy not only for your current team, but your future contributors to improve the product.

Finally, I’ve avoided discussing the plugin that Pippin, Andrew, and I built specifically because I wanted this post to be about the process, not the product; however, now that we’ve covered the former, you can find the latter here on GitHub. If you’re interested, feel free to leave us issues, notes, or even pull requests!

Original from: http://feedproxy.google.com/~r/Wptuts/~3/L-j-NNeAuik/

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/

Quick Tip: After the Content – Post Meta

April 5th, 2013 Comments off

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

Human or crawler, a visitor needs to find where your post belongs. Even if you have category or tag archives, it’s almost always a necessity to include a section to display a little bit information for the content.

In this post, we’re moving on with our series with the “post meta”, the identity card of the post.

/>

“Post Meta” to Help People (And Crawlers) Find Their Way

While a “related posts” section is the most effective way to offer people relevant content, it’s also good practice to serve the information of the post’s categories, tags, publishing date and so forth – both for humans and search engine spiders.

Why Use a “Post Meta” Section?

I don’t know if you have ever done this, or have seen someone else do it, but sometimes people like to consume the content of a website as a whole.

You might have come across some weird data in your website’s statistics, which showed that one visitor (or a couple of visitors) spent over 3 hours on the website. If you have good content, the chances are higher to see weird data like this in your website’s stats.

This kind of content consumer is the kind who will constantly share your posts and talk about your website. You must care about these people the most and in order to help them spend hours in your website, you must provide them with a well structured post meta section.

The same goes for “normal” visitors: They might be interested in other posts from the same category or author, or they might want to know when the post was published. Also, of course, search engines always need information to categorize and structure your website’s page listings.

Creating a Strong “Post Meta” Section

In order to serve a “post meta” section with good quality, we must think of what it should consist of. Off the top of my head, I can list a couple of items:

  • The author of the post (with a link)
  • The categories that the post is in
  • The tags the post has
  • The publish date of the post
  • A link to edit the post (for admins and authors, of course)

Naturally, WordPress provides core functions for these elements: the_author_link(), the_category(), the_tags(), the_date() and edit_post_link().

This is not a section that requires attention, so there’s no need to shine through – three lines is enough for the post meta, I think. So, if we put them together, we can build something like this:


Done! Simple and effective.

/>

Conclusion

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

We now know the essentials of the “post meta” section – why use it and how to use it effectively. If you have anything to say, please share your comments with us!

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