Book Image

WordPress 3 Plugin Development Essentials

Book Image

WordPress 3 Plugin Development Essentials

Overview of this book

WordPress is one of the most popular platforms for building blogs and general websites. By learning how to develop and integrate your own plugins, you can add functionality and extend WordPress in any way imaginable. By tapping into the additional power and functionality that plugins provide, you can make your site easier to administer, add new features, or even alter the very nature of how WordPress works. Covering WordPress version 3, this book makes it super easy for you to build a variety of plugins.WordPress 3 Plugin Development Essentials is a practical hands-on tutorial for learning how to create your own plugins for WordPress. Using best coding practices, this book will walk you through the design and creation of a variety of original plugins.WordPress 3 Plugin Development Essentials focuses on teaching you all aspects of modern WordPress development. The book uses real and published WordPress plugins and follows their creation from the idea to the finishing touches in a series of easy-to-follow and informative steps. You will discover how to deconstruct an existing plugin, use the WordPress API in typical scenarios, hook into the database, version your code with SVN, and deploy your new plugin to the world.Each new chapter introduces different features of WordPress and how to put them to good use, allowing you to gradually advance your knowledge. WordPress 3 Plugin Development Essentials is packed with information, tips, and examples that will help you gain comfort and confidence in your ability to harness and extend the power of WordPress via plugins.
Table of Contents (19 chapters)
WordPress 3 Plugin Development Essentials
Credits
About the Authors
About the Reviewers
www.PacktPub.com
Preface
Index

Basic organization


The simple recommendation here is to keep your code consistently organized. If someone is looking through your code months from now, will he be able to follow the method to your madness? If you are consistent, people will be able to follow your logic more easily, even if they don't agree with it. Consistency should prevail throughout your variable names, function names, documentation, file names, and folder structure: keep it sensible and clean.

One other tip that we have learned through many hours of frustration seems profoundly simple: a "unit" of code should fit on one screen without scrolling. In general, if you can't see it, you can't get it uploaded into your brain for full comprehension. What is a "unit"? Usually it is a function, but sometimes it can be a logical block or a group of related tasks. Functions are easier to test, so they make for better units. The bottom line is to take small bites and if your "units" fit snugly on the screen instead of scrolling across several pages, then your code will be much easier to understand and debug.

Here are the main points to consider when organizing your code:

  • Isolate tasks into functions

  • Use classes

  • Use descriptive variable names

  • Use descriptive function names

  • Separate logic and display layers

  • Go modular, to a point

  • Avoid short tags

Isolate tasks into functions

A function, as its name suggests, performs a certain task, but structuring them can be a bit of an art. Any time you find yourself copying and pasting identical code (or even similar code), that should be a glaring red flag that it's time to consolidate it into one place by putting it into a function. Just like having a single stylesheet for your website gives the designer a single place to make global changes, a function should give the developer one place to alter a particular behavior.

A good rule of thumb when writing functions is that they should not accept more than three inputs. Otherwise, they become difficult to use. You can package multiple inputs into a single associative array (a.k.a. a "hash"), or you could restructure your code into multiple functions. Again, find a clean solution.

Use classes

For new developers, the whole notion of objects and classes may seem something of a black art. It may feel needlessly complex, and to be fair, in some scenarios it is. However, the more you develop, the more you will gravitate toward object-oriented code because it allows for better organization, maintainability, and classes are much easier to extend.

Anyone familiar with CSS can appreciate the beauty of overriding a behavior. In the same way that you can override a style declaration from a *.css file with a local declaration, you can override a PHP class function by extending the class and redefining the function. We will see some examples of this later in this book.

Use descriptive variable names

PHP does not impose many restrictions on variable names, and there are differing naming strategies that you may employ. Compare this to Java, where using the incorrect case or underscores in your variable names is tantamount to heresy. Common naming strategies include $lower_case_with_underlines and $camelCase, and since PHP does not use distinct glyphs to distinguish arrays from scalar variables (like Perl, which distinguishes a $scalar from a @array), it can be useful to include the data type in the variable name, for example, $records_array.

Whichever method you use, make sure that the names adequately describe the contents of the variable in the context in which they appear. Avoid single letters and avoid long-winded, overly complicated names. In general, find the shortest name that accurately represents the variable's purpose. It may seem esoteric, but in order to understand your code, it must enter your brain through the construct of the English language (or in whatever language you tend to think). If your variable names are unclear, your brain will have to work harder to understand what your code is doing, so take the time to be descriptive and clear.

Use descriptive function names

As with your variable names, your function names should accurately describe what the functions do. It is common in most languages to have functions that get or set attributes, such as getHeader() or setPageWidth().

There are a few caveats to mention with PHP function names: first of all they are not case sensitive. For example, add_action(), aDD_aCtIoN(), or ADD_ACTION() are all interpreted identically. For the sake of clarity and ease of searching, always call your functions using the same case as their definitions.

Function names starting with a single underscore (for example, _my_private_function()) have historically been used to denote private functions—that is functions intended for use by other functions and not for direct use by the "outside world". With PHP 5, you can control the access to a class's functions as public, private, or protected, but the underscore is still often used as a helpful reminder.

"Magical" functions in PHP use names starting with two underscores (for example, __construct()). They are used to perform special tasks inside of a PHP class. Although you can name your functions in this way provided there are no name collisions, it is not recommended because they may be mistaken for magic PHP functions. For example, WordPress uses the __() function for localization, but we do not recommend using function names that begin with two underscores or whose names are very non-descriptive.

Lastly, your code will be much easier to navigate if you alphabetize your functions by name. Some text editors, particularly IDEs, will provide a menu to jump to each function. Alphabetizing works especially well if you put the magic functions (with two leading underscores) before the private functions (with a single leading underscore) before the public functions (with no leading underscores). The quicker you can navigate your code, the quicker you will be able to debug and change it.

Separate logic and display layers

It doesn't matter whether you are using procedural or object-oriented code, you should still separate your logic from your presentation. In laymen's terms, that means that you should keep if-statements, loops, or any other logical flows out of your HTML as much as possible.

Endlessly concatenating bits of HTML with variables and having to debug your display layers is a huge waste of time that is accepted as common practice by a staggering number of developers. You will be way ahead of the curve if you keep your HTML display logic as simple and static as possible, and keep your complicated calculations in separate functions and files. We will show you several examples of how to avoid messy concatenations using PHP functions like sprintf() as well as a few of our own parsing functions.

Go modular, to a point

Normally, there are strong admonitions to reuse your code whenever possible, but it is necessary to mention the caveats required for making your code portable and modular. When it comes to plugin development, sometimes you can get into trouble if your code pokes its head too far out of its own folder and starts referencing JavaScript libraries, CSS files, or even scripts that it assumes will be present in any WordPress install.

The only tie to the parent application should be through the API. It may go against your instincts to copy a second version of an image or a JavaScript library into your plugin's directory, but it will ensure that your plugin is self-sustaining and not susceptible to changes outside of its own folder.

Avoid short tags

Simply because you can configure PHP to use "<?" and "?>" (a.k.a. "short tags") to demarcate PHP code, that doesn't mean you should. Short tags are fool's gold! Even if your web server supports them, don't expect everyone in the neighborhood to join your club. Apart from making distribution of your plugin risky, short tags can cause XML files to get interpreted as PHP because they too begin with "<?".

We have personally discovered many plugins in the WordPress repository that made the sophomoric mistake of using short tags, forcing us to have to debug them immediately after installing them. It sounds harsh, but using short tags is a sure-fire way to doom your plugin to the rubbish pile.