Archive

Posts Tagged ‘web development’

Take Your Skills to the Next Level, Build Your Own Plugins

May 18th, 2013 Comments off

There are only a few Early Bird tickets left for our 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!

Tom is going to teach you how to write a WordPress plugin that connects to the is.gd API in order to implement an alternative URL shortner to the built-in wp.me shortner.

The goal of the plugin is to demonstrate:

  • How to write an object-oriented based plugin.
  • How to interface with a third-party API.
  • How to introduce a custom meta box.
  • How to perform input validation and sanitization.
  • 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/iXBVq3u8XV8/

PHP Tutorials for Beginners

May 14th, 2013 Comments off


You have probably heard that PHP is much easier to learn than any other programming languages, such as Java or the .NET languages, not to mention Perl, but if you are new to PHP, it can be daunting. If you are new to PHP, we are here to help.

The first block of tutorials are more general and cover the basics of PHP as a language, such as variables, conditionals, HTML forms, loops, arrays, strings, functions… While the second block of tutorials are all about performing a particular task, such as creating captchas, building forms, and even building a complete CMS.

Now remember, take your time with each tutorial and enjoy!

PHP Logo

A Simple Tutorial from php.net

It doesn’t matter what kind kind of information you are looking for, it is always best to start at the source. This, of course, applies to learning PHP as well, the very site of the PHP programming language: php.net.

I am not saying this tutorial is the easiest, but it is a great tutorial for getting started with. It is more like a general introduction to PHP than a complete guide. Iit is split into the following sections:

  • What do I need?
  • Your first PHP-enabled page
  • Something Useful
  • Dealing with Forms
  • Using old code with new versions of PHP
  • What’s next?

The tutorial should only take you about 15 minutes to complete – providing you don’t check all the hyperlinks to the other pages. If you do, it will probably take weeks to complete.

A Simple Tutorial from php.net →

Beginners PHP (Complete Course)

This tutorial is a much longer and more in-depth that the tutorial above. It covers all the basics of PHP, such as variables, conditionals, HTML forms, loops, arrays, strings, functions, security, file manipulation, MySQL, user authentication. At the end of the tutorial you will find chapters on how to code sample apps, such as polls and online forums.

This is a long tutorial and you may have to go through some chapters more than once, especially if you are new to PHP. So, you will need at least a day or two to go through it all.

Beginners PHP →

Introduction to PHP (Complete Course)

If you are a fan of video tutorials, then you will love this PHP Course. There are over 200 videos available and they cover absolutely everything about PHP. The series covers all aspects of PHP, such as how to install XAMMP, how to create your first PHP file, input/output, variables, conditionals, operators, loops, commonly-used functions, strings, arrays, sample applications, etc.

It’s a huge resource and if you want to learn absolutely everything, you will need weeks to cover it all. Each video is reasonably short, though – from 1 to 10 minutes, so you can watch a couple of them in a day, revise them on the next day, and thenmove onto the next video.

Introduction to PHP →

PHP 101: PHP For the Absolute Beginner (Complete Course)

This is another complete PHP course that walks you through the basics. As with the other courses, it covers everything – variables, operators, loops, functions, arguments, MySQL, object oriented programming, sessions and cookies, error handling and security. It even includes two tutorials for building sample applications – such as a simple web application and an RSS news aggregator. Similarly to the other complete courses, this one will take at least a couple of days to read, learn, and revise.

PHP 101: PHP For the Absolute Beginner →

MySQL PHP Tutorial

The tutorials so far include sections on MySQL and how to use it with PHP, but since PHP and MySQL are used together [almost] all the time, it wouldn’t hurt to cover a tutorial that focuses solely on MySQL.

This tutorial explains how to create a new MySQL database, connect to it, create users and give them permissions, write a simple script, create and populate a database, retrieve data, escape characters, print column headers, count fields and rows, write and read images, and use transactions.

The following is a simple PHP script example from the tutorial:

If you are already familiar with the SQL syntax this tutorial should only take you 2-4 hours.

MySQL PHP Tutorial →

PHP OOP Tutorial from Beginner to Advance

This multipart tutorial series focuses on PHP from the object oriented programming (OOP) point of view. It starts nice and gently, so even if you are a beginner to both PHP and OOP, you will be able to follow along easily. The first part covers the basic concepts of OOP, such as objects, abstraction, inheritance, encapsulation, and polymorphism, but the following parts delve much deeper.

This tutorial will take you no more than 15 minutes (including the time you need to test the examples). However, the foloowing tutorials in the series are much longer and more complicated, so for each of them you might want to devote half an hour or more.

PHP OOP Tutorial →

List Files and Directories with PHP

Lists of files and directories are very common in web development. This tutorial will show you how to list files and directories with the glob() function, a combination of the opendir(), readdir() and closedir() functions, and the scandir() function. You will also learn some advanced file/directory listing techniques – SPL iterators, such as the FilesystemIterator, the RecursiveDirectoryIterator, and the GlobIterator.

The tutorial isn’t as complex as it might at first seem, but you probably should budget at least 45 minutes to complete it. It could even take longer, if everything is not working as expected and you need to make some fixes.

List Files and Directories with PHP →

Creating Your First PHP Application

We are definitely way beyond the basics with this tutorial. In fact, it’s a series of tutorials that cover the following:

Part 1 – Setting up the project and creating your first class

  • Creating an outline of the project
  • Setting up your files and folders
  • Creating a class to handle database operations: DB.class.php

Part 2 – Building the rest of the backend

  • Creating a User class
  • Creating a UserTools class
  • Registration / Logging in / Logging out

Part 3 – Building the front end

  • Forms
  • Form Handling
  • Displaying session data

As you can see this is a large tutorial, so budget at least a couple of days to complete it.

Creating Your First PHP Application →

How to Process Credit Cards with PayPal Payments Pro Using PHP

For a shopping site, credit cards payments are a must. There are many ways to accept credit card payments but PayPal is the most popular. In order to complete this tutorial you will need to have a merchant account with PayPal. The steps you need to follow are: create the directory structure, setup the config file, create an API request, send the HTTP request to PayPal, and parse the API response (there two approaches).

This isn’t the simplest tutorial, so you will probably need at least an hour or so to complete it.

How to Process Credit Cards with PayPal Payments Pro Using PHP →

Automatic CSS3 Prefixer and Compressor Tutorial

CSS files are text files but they can be very large. That is why they will benefit from some compression. Additionally, instead of writing all CSS3 properties with browser-specific prefixes by hand, this can be automated with PHP.

Automatic CSS3 Prefixer and Compressor Tutorial

This tutorial will teach you exactly how to do this: Generate CSS3 properties with browser-specific prefixes, how to concatenate (had to look this word up, it means ‘ linked together, as in a chain’ – Editor) all the CSS files to save space and reduce load time, and how to do both automatically when a web page is requested.

The estimated time to complete the tutorial is about an hour.

Automatic CSS3 Prefixer and Compressor Tutorial →

Create Your Own Captcha in PHP

This short tutorial has been written in a typical programmer’s fashion, meaning it has little to no explanation, short to missing comments, and the assumption that everything is obvious and clear. However, aside from this, it is a useful tutorial and the slightly more advanced programmers might love it just because it uses few words and plenty of code.

Create Your Own Captcha in PHP

The tutorial is short, so it won’t take you more than 20 minutes.

Create Your Own Captcha in PHP →

Getting Started with PHP Regular Expressions

And now a tutorial on everybody’s favorite: regular expressions. Unfortunately for everybody who hates them, regular expressions are pretty useful, though often you can bypass them with other techniques.

Create Your Own Captcha in PHP

The tutorial in the link explains what regular expressions are, the Perl compatible regular expressions, the basic syntax of PHP regular expressions, how to use regular expressions in PHP, useful regex functions. Additionally, the tutorial includes a cheat sheet where all the basic stuff is gathered in one neat place.

The tutorial could take you an hour or two to complete but this depends on your familiarity with regular expressions. If you are a total stranger to them, expect to read some sections multiple times and, naturally, this will take you much more time.

Getting Started with PHP Regular Expressions →

Simple Banner Rotator With PHP, jQuery & MySQL

This tutorial goes beyond PHP, but since in real life that is exactly what you need, that is why the tutorial is included here. First you need to create the database schema, then the XHTML code, then the CSS, and only after that you will move on to the PHP side of things.

Simple Banner Rotator With PHP

The tutorial will take you at least 2 hours to complete, and that is if you don’t have to make a lot of modifications to the code.

Simple Banner Rotator With PHP, jQuery & MySQL →

Build a CMS in an Afternoon with PHP and MySQL

If we are honest here, this tutorial will probably take you more than an afternoon to complete. Having said that, it also isn’t as hard as it seems. In order to create the CMS, you do need to be familiar with the SQL syntax and MySQL, so if you do lack knowledge in these areas, first check the tutorials that teach MySQL above and then come back to this one.

Build a CMS in an Afternoon with PHP and MySQL

The CMS you will be learning to build will have all of the basic features you would expect from a CMS.

The frontend will have:

  • Homepage with the 5 most recent articles
  • Article Listing Page (archives), where snippets of all articles are displayed
  • A “View Article” page (single post), where visitors can read the entire article

The backend will have:

  • Admin login/logout
  • List of all articles
  • Add a new article
  • Edit an existing article
  • Delete an existing article

Build a CMS in an Afternoon with PHP and MySQL →

PHP Script Image of the Day

This tutorial shows you how to create a PHP script image of the day. All you need to do is find today’s date (with the help of the date function), store the value in the “$today” variable, and compare $today with the name of the day. Then you display the message “Today is ” … ” (you can modify the message, of course), together with the image of the day.

PHP Script Image of the Day

The estimated time for the completion of the task is about 10 to 15 minutes. This however doesn’t include the time to search for the images to display every day, so you may want to prepare them in advance.

PHP Script Image of the Day →

PHP is fun and it can be used for so many tasks. These tutorials won’t make you a PHP guru but they will help improve your skills and hopefully allow you to develop more complex PHP applications.


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

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/

Learn WordPress Plugin Development with Tuts+ Live Workshops

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/

Tuts+ Premium Cash Back Offer: 3 Days to Go

May 8th, 2013 Comments off

This offer ends soon! Act now and don’t miss out on cash back when trying a monthly Tuts+ Premium 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.

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

Become a Tuts+ Premium Member and take your creative & 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/

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/

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/

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/