With WordPress becoming more and more popular there is a massive amount of code being generated by users, agencies and marketplaces. I've been working with WordPress for a long time and it amazes me how many developers out there are making the same mistakes over and over again.
I'm going to go through some of the most common development mistakes and how you can easily fix them, and going forward make your code better!
Why Your Code Sucks
If you do a Google search for "WordPress" it returns 1.9 Billion results. There are millions of sites with code examples, tutorials and snippets that come in very useful as a WordPress developer. The trouble is 2 fold:
- People don't follow WordPress coding standards
- People just copy and paste
So as a new WordPress developer you do a Google search, find an article, copy and paste the code and it works! Brilliant you say to yourself and you remember or bookmark the code. The big problem here is that the code may not be perfect, but you're new so you won't notice. As it works you may simply keep using it forever.
Let's get started on how you can avoid some common mistakes!
WordPress Coding Standards
WordPress themselves admit that some parts of the WordPress code structure for PHP markup are inconsistent in their style (their exact words). They are working through to clean up the code and make it consistent and have set out a standard for ALL WordPress code. It doesn't matter whether it is a Plugin or a Theme they should all follow the same standards.
If you have never read this page before read it! This should be one of the first places any developer working with WordPress visits. I'm not going to go through the points here but you should take the time to go through and read it.
I myself am guilty of breaking a couple of these rules, but the real key is consistency. The one rule I do break I break all the time. Personally when dealing with if
statements I prefer to use the Alternative Syntax for Control structures. For me they are easier to read. By being consistent throughout my code at least people can see instantly I am doing something different and follow me through my code.
Remember: Consistency and coding standards really do go a long way to making your code look and read better!
Codex, Codex, Codex
In the previous section we looked at the WordPress Coding Standards, this document is found in the single most useful development resource for WordPress developers. The WordPress Codex. Available in nearly 50 languages the Codex is the developers bible. It contains documentation on almost every single function, class and variable within WordPress, how to use them and code examples. I usually have 3 or 4 tabs open on the codex at any one time, in fact at the moment I have 4 open! It doesn't matter if you're new to WordPress or have been working with it for years the documentation here is invaluable.
The beauty of the Codex is that it is a living, breathing community for documentation. You can contribute your own knowledge to make it better or add a page if it's missing, just remember if you do add any code to follow the WordPress Coding Standards!
My biggest piece of advice for the Codex is to search! As with any Wiki based site, navigation is a little tricky and doesn't necessarily make any sense at first. The built in search should help you find what you're looking for. If you are struggling to find what you are looking for then jump into the #WordPress IRC channel, there are usually a few people in there who will point you to the right Codex page.
The Right Tool for the Right Job
So now we know about coding standards and where to get the right documentation and help let's have a look at some of your code.
<head> <link rel='stylesheet' href='style.css' type='text/css' media='screen' /> <script type='text/javascript' src='js/mysite.js'></script> <title>Hello</title> </head>
The above snippet is the typical first few lines of most WordPress themes, however it shouldn't be. Scripts and styles can be handled so much better with WordPress and they give us some great functions for working with them. Now I'm talking here about themes, but any plugin that needs scripts or styles should be doing things exactly the same way. Introducing wp_enqueue_style()
and wp_enqueue_script()
! If you don't know what these functions do then we need to fix that! Let's go through what you need to do.
Let WordPress Know All About It!
Regardless of whether it is a script or style the best thing to do is to let WordPress know about it. We do this by using wp_register_script()
or wp_register_style()
. These are both the safe ways of registering a script or style with WordPress so you can use them later on. Now this function doesn't output anything to your theme or site, it simply prepares WordPress for using them.
<?php wp_register_script( $handle, $src, $deps, $ver, $in_footer ); wp_register_style( $handle, $src, $deps, $ver, $media ); ?>
$handle
(Required) This is your name for the stylesheet or script. This can be anything you like as long as it is unique. You can always prefix the name to avoid conflicts.
$src
(Required) This is the URL to the stylesheet or script. It can either be external or internal to your site depending on what you are doing. External is useful if you are using a thrid party font service like Type Kit or Google Fonts or for Social Media Javascript. You should never hardcode the URL for local stylesheets or scripts, there are proper functions you can use for this which we will discuss later.
$deps
(Optional) This is a very useful one although it is optional. This allows you to specify an array of dependencies for your script or style sheet. It will also then ensure those dependancies are loaded before your script or style is.
$ver
(Optional) Here you get to specify the script or style version number, if it has one. This is useful to ensure that the correct version is sent to a user's browser regardless of caching. Of course you can set your own version numbers for your own scripts and styles or you can use a nice little trick to get dynamic version numbers.
$in_footer
(Optional, Script Only) Normally scripts are placed in the <head>
however if you set this parameter to true the script will be placed at the bottom of the <body>
. If you do want to output in the footer then you do need to make sure your theme has the wp_footer()
hook in the right place.
$media
(Optional, Style Only) This can be a string to specify the media that the stylesheet has been defined for. (Eg. 'all'
, 'screen'
, 'handheld'
, 'print'
).
Let's put it all together in a nice example:
<?php function tuts_register_stuff() { wp_register_script( 'my-script', get_template_directory_uri() . '/js/my-script.js', array( 'jquery' ), 1.0, true ); wp_register_style( 'my-style', get_template_directory_uri() . '/style.css', array(), 1.0, 'screen' ); } add_action( 'wp_enqueue_scripts', 'tuts_register_stuff' ); ?>
Very briefly, we have a JavaScript we are calling from our theme folder, it is dependant on jQuery, set to version 1 and we want to output at the end of our page. Also we have our style.css that we are calling from our theme folder, it has no dependancies, is version 1.0 and is for screen. It is also important to remember that we need to actually execute these scripts by using an action hook. In this case we use wp_enqueue_scripts
as our action hook as recommended by the Codex.
It's all very easy once you get the hang of it and get into the habit of doing it!
Let WordPress Do the Heavy Lifting
Now we have registered our scripts and styles WordPress knows all about them and now we can start to use them. Going back to our wp_enqueue_script()
and wp_enqueue_style()
we can now enqueue the styles and scripts that we registered in the previous step. The enqueue script and style functions work very similarly to the register functions. The big difference is that WordPress will now output the JavaScript or style to the page it generates.
<?php function tuts_enqueue_stuff() { wp_enqueue_script( 'my-script' ); wp_enqueue_style( 'my-style' ); } add_action( 'wp_enqueue_scripts', 'tuts_enqueue_stuff' ); ?>
Because we have already registered our scripts and styles enqueuing them is super simple. The beauty of this is that we can conditionally enqueue our scripts and styles so we only load them on the pages that they are needed on. Also as they are being called in the same action hook you can do them all in one function. Take a look at the example below:
<?php function tuts_scripts_and_styles() { wp_register_script( 'global', get_template_directory_uri() . '/js/global.js', array( 'jquery' ), 1.0, true ); wp_register_script( 'home-page', get_template_directory_uri() . '/js/home-page.js', array( 'jquery' ), 1.0, true ); wp_register_style( 'global', get_template_directory_uri() . '/style.css', null, 1.0, 'screen' ); wp_register_style( 'sliders', get_template_directory_uri() . '/css/sliders.css', null, 1.0, 'screen' ); if ( is_home() ) { wp_enqueue_script( 'home-page' ); wp_enqueue_style( 'sliders' ); } wp_enqueue_script( 'global' ); wp_enqueue_style( 'global' ); } add_action( 'wp_enqueue_scripts', 'tuts_scripts_and_styles' ); ?>
So we have registered our styles and scripts the correct way and have enqueued them. We also have a script and style only being enqueued on our home page using a conditional statement.
This is a perfect example of one of the biggest mistakes I see when looking at themes or plugins written by others. By learning a couple of easy WordPress functions you can load your styles and scripts safely and make sure all the dependancies are in place. Also if someone is using a plugin you have written it is easy for them to make changes without having them wiped out by updates. All they need to do is copy your CSS to their theme, and they can un-register your style and register their own!
You can see a full tutorial on how to use these functions at the bottom of this tutorial.
Your JavaScript Kills Kittens
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
If you have ever put this in your theme, plugin or anything to do with WordPress you just killed a kitten. We have already discussed the importance of registering and enqueueing your scripts and styles so why undo all your hard work. WordPress comes bundled with loads of scripts for you to use simply by enqueuing them. Of course you can, even when doing things correctly, you could unregister the bundled version of a script and register your own version. As above, maybe we want to use the Google CDN version. This is fine if you are working on your own site, your own private theme or plugin and you are not going to be releasing it. However if you are publicly releasing your code stick to the included libraries. Other plugins may break, themes might stop working all because no one is following the rules. I often find sites with 3 or 4 different versions of jQuery loaded up simply because people aren't registering and enqueuing properly or some plugin author wants to use a different version of something.
Let's do each other a favour and follow some standards!
Warning: Plugins or themes that use a non-bundled library will be rejected if submitted to both ThemeForest and the WordPress.org repository!
Now it is also important to briefly talk about jQuery. It is massive, everyone uses it, themes love it and plugins love it. However it can cause problems if it's not used correctly. The jQuery library bundled with WordPress loads in "no conflict" mode. This allows it to work along side the other libraries that WordPress can use. However in no-conflict mode the $
shortcut doesn't work and has been replaced with the slightly longer jQuery
.
$(document).ready(function() { $(#myfuntion) ... });
The above needs to be re-written to work, the easiest way is to use the following wrapper:
jQuery(document).ready(function($) { $(#myfunction) //Now $() works as an alias for jQuery() inside this function! });
The trouble with loading an external version of jQuery is that it may not load in no-conflict mode, it can break other scripts and the author may have written JavaScript without following the above rules. Meaning it all breaks when you try to use the bundled jQuery version! Always try to use the bundled libraries and always write your JavaScript/jQuery in no-conflict mode!
You can get more information on WordPress and jQuery in the Codex Page.
Find Your Way Around
How do you get your theme directory path? How do you direct people to the home page of the site? A lot of developers still don't really know how to do some basic things with WordPress. I'm going to pull out a few of the most common.
-
Getting the theme location: If you are using
TEMPLATEPATH
orbloginfo( 'template_directory' )
. Stop! You should be using the very usefulget_template_directory()
as seen in my examples above.There are actually 4 variations of this function:
-
get_template_directory()
returns the PATH to your theme folder. Useful for use inside PHP functions or includes. -
get_template_directory_uri()
returns the URL to your theme folder. Useful for enqueueing and registering your scripts and styles and if you want to include and image. -
get_stylesheet_directory()
returns the PATH to the stylesheet folder. This will always point to the Child Theme if one is in use whereasget_template_directory()
will always point to the Parent Theme. -
get_stylesheet_directory_uri()
returns the URL to the stylesheet folder. As with the above this will always point to the Child Theme if one is in use.
Make sure you use the right function. If you are expecting users to override your theme in a Child Theme then it is best to use the correct function.
-
-
Getting the plugin location: With plugins there are 2 different functions to use:
-
plugin_dir_url()
returns the URL of the plugin file passed in. -
plugin_dir_path()
returns the directory path of the plugin file passed in.
With plugins I always find it easier to define a constant right at the start and use that throughout my plugin.
<?php if ( ! defined( 'MY_PlUGIN_URL' ) ) define( 'MY_PLUGIN_URL', plugin_dir_url( __FILE__ ) ); if ( ! defined( 'MY_PLUGIN_PATH' ) ) define( 'MY_PLUGIN_PATH', plugin_dir_path( __FILE__ ) ); require_once( MY_PLUGIN_PATH . '/my-file.php' ); ?>
-
-
Getting your site URL: It's a fairly common requirement, maybe you want to simply add a link to your home page? Like getting the theme directory stop using
bloginfo()
. The example below gives a very basic example of how to do it correctly.<a href="<?php echo home_url( '/' ); ?>">This is a link to our home page</a>
If you're in doubt of anything then read the Codex it really does help! By using the correct functions to get you around WordPress you make it much more likely that your plugin or theme won't clash or interfere with others' code. There is nothing more frustrating than trying to troubleshoot a bug in your own code only to find it is another plugin that is messing everything else up!
Plugin or Theme?
This has been a talking point amongst the community for ages. Should I put my functionality inside my theme or in a plugin? I always find that the simple answer is this: will your functionality work if you were using a different theme? What I mean here is if you are adding extra functionality, maybe a custom post type or a custom lightbox effect for images, will it work with any theme or can it work with any theme? There is nothing worse than spending ages setting up a site with loads of lovely custom post types adding loads of content only to find you change theme and it all just disappears.
I usually follow this simple rule, if it can be a plugin make it one. Themes are meant to specifically deal with the visual style of a site not the functionality. Plugins are for functionality. Now if your plugin is outputting something, as most of them are, you can easily check your active theme for the required template files and fall back to your plugin's template files if need be. In fact in most cases my plugins come like this. At least then you give the user the chance to modify the way it looks without losing their changes if you publish an update. I will try to cover this in a future tutorial, however the lesson here is to keep it simple. Breaking your functionality up in to nice bite-size chunks give the user the choice, if they don't like your Social Sharing buttons, let them switch them off or replace them with their own. More plugins, less overly complicated theme options pages!
Action Filters and Hooks, Why You No Use Them?
This is another point that I wanted to raise very briefly as I know there are some great tutorials out there on Actions and Filters (one is linked at the bottom for you). No matter what kind of WordPress development you are doing, learn about Actions and Filters. This is one of the biggest mistakes I see people make. WordPress has a great API for theme and plugin development and you can make your development much better by using the tools that WordPress puts out there for you. The best plugins out there make extensive use of Actions and Filters so that if you do want to customise how it works for you it's simple.
An example of this is WooCommerce from WooThemes. Now whilst I'm not a fan of the massive theme options panels they put in their themes, WooCommerce has been built with other developers in mind. Almost everything can be customised or overridden by simply removing actions or replacing them. Their Action and Filter Reference is extensive and really does allow you to work along side it exactly how you want to. Now I don't expect you to go to this extent for your own projects but we can learn important lessons here. If your code is easy to customise without hacking it to bits then people are more likely to use it, review it and recommend it!
Actions and Filters are one of the most important things you should learn about WordPress development, take some time and you will get there!
Conclusion
We've covered a lot in this article and I hope it was of use. I want to just break it down even further for you:
- Follow the WordPress Coding Standards
- Be consistent with your code
- Use the documentation! The Codex is your bible
- Use the functions that are there for the right reasons
- Think about where you put your code
- Make use of Actions and Filters
When you copy and paste that code you found from Google take a minute to look at it, understand it and try to apply the above to it. Does it follow the Coding Standards? Is it using the correct functions? What is that jQuery doing? You are only 1 theme or plugin away from all these points becoming second nature. Next time you see a mistake, try to fix it!
Comments