10 WordPress Code Formatting, Optimization and Performance Tips

Tuesday, July 30, 2013


Advertise here with BSA




WordPress is one of the easiest CMS to get started, with a lot of available plugins, themes and tutorials. But it’s also easy to get lost, write some bad code, and doing things that will certainly cost you a good time to fix in the future.


WordPress has a simple guide on code formatting and our intention is not to just replicate that, therefore we’ll take it to the next level and learn a little bit of everything when it comes to code organizing, performance and optimization.


One important thing also is to always use “future proof” solutions. WordPress code, themes and plugins are being updated all the time so you should make your code as easy as possible to debug and modify.


So, here we are with a few tips that will make your “future you” much happier. Some may seem too simple, such as code indentation and spaces, but in fact all of them are simple to implement and you’ll notice how better your code will be after this makeover.


Let’s get our hands dirty then!


#1 Consider creating all your functions inside of a class


When you’re creating your own plugin, you may need to create some common functions with rather common names like read_rss or seo_head. There’s a big chance that someone else has already created a function with this name, and if the user activates a plugin or theme with a duplicated function name he / she will get an ugly PHP error.


So a good recommendation is to wrap all functions inside of a big class then even if someone else has created a function with the same name as yours it won’t break anyone’s code since yours is only reference in the class.


#2 Always prefix your function names


If adding an entire class seems a lot of work for you, you could consider prefixing your functions with something that will be simple but different enough to avoid breaking other people’s code.


For example, if your plugin is called Awesome WordPress WhiteLabelling you could create a prefix like aww_FUNCTIONNAME() so all your functions will look both cute and unique at the same time.


#3 File naming conventions


When you need to search for a theme function, which file do you look first? I bet most of you would simply open the “functions.php” file under the theme folder. And what if you need to edit a plugin? Well, then you might want to search for a file with the same name as the plugin.


So there are quite a few common practices that may help you finding other people’s code and also creating your own:



  • General theme functions usually are under functions.php, unless it uses a framework

  • General plugin functions are in the file with the same name as the plugin folder

  • Wp-Admin related functions (like custom fields, widgets, theme options…) usually are in a separated file, in the /admin folder under theme folder

  • Images, CSS, and JS files are usually in their own folders (except the style.css file, which should always be in the main theme folder)

  • Page templates are usually prefixed with “page” or “template”, so it’ll be something like this page-TEMPLATENAME.php


#4 Empty space is important in your code also


How do you feel when you visit a site where every single pixel has been filled with some kind of information? When there isn’t space for the design elements to breathe?


Imprisoned, is probably the adjective you’re looking for.


The same rule applies to your code, if you don’t leave a few blank spaces in your code, it gets hard to read. Remember, most people only scan when they’re using computers, and you do the same thing.


So, instead of something like this:



<?php $myvar=14; $anothervar = "It's cool to add variables in the same line";
if(!$myvar==15){
echo "Almost there!";
}

$args = array( 'this' => 'is', 'getting' => 'quite', 'confusing' => '!!!' );
?>

Use something like this:



<?php
//always leave the opening "php" tag alone, so you'll clearly know when it starts

//add a tab or two if you want to align the variable values
$myvar = 14;
$anothervar = "It's cooler to have them in separated lines";

if( ! $myvar == 15 ) { //SPACES EVERYWHERE, including before & after the "!", "(", ")", "{" and so on
echo "Almost there!"; //indent your code, bro!
}

$args = array(
'this' => 'is',
'getting' => 'quite',
'much' => 'clearer' //easier to read if each item is in a separated line
);
?>

It may be hard in the beginning but you’ll notice how good it’ll be to just scan your code and know exactly what each “if” clause is for.


#5 Underscore is for functions, hyphen is for folders


This is the common practice for a couple of good reasons. The first one is that folders and files are also URLs, and hyphen is not a nice URL character (not as good as hyphen, that is commonly used as a replacement for spaces even in domain names)


We should mention as well that function and variables sometimes need a 2-word-name, and camel case is not a common practice in the WP world.


#6 Don’t Java me


I’ve met a few programmers that came from the Java world and they are quite used to a few things that are really strange in this land. Check this code:



<?php
function addCustomPostMeta()
{
$seriously = "why??";
}
?>

This is certainly strange for PHP eyes, something like this looks much better:



<?php
function add_custom_post_meta() {
$better_now = "right??";
}
?>

#7 Disable the Shorthand at your localhost


A lot of guys feel tempted to use the PHP shorthand, like this:



<?=$myvar ?>
<!-- OR -->
<?
//can you find what's wrong here?
?>

While this is certainly an easier notation, it’s harder to read but most important, it won’t work in all servers. So in order to avoid user complains just disable it and code as it doesn’t exist. Pretty much the same thing as we were used to do when IE6 were still around.


Just ignore it, because it won’t ever work as you told it to.


#8 Load files only when you need them


Remember what we said about keeping your wp-admin related files separated? Here is one of the good reasons: You can improve your plugin performance drastically by doing so.


The sad and true story is, WordPress will call your functions.php file every time it loads, and this may consume a lot of time if you have external includes (since it needs to make sure that it’s not missing any action or filter). So you can use something as simple as this to make sure it will only be loaded when a logged in user is trying to load it:



<?php
if ( is_admin() ) {
//WordPress will only load this file when we're in the /wp-admin area
include("admin/functions.php");
}
?>

#9 Use the debugger style comment and function


While coding you may need to isolate a few code blocks, so this function may come in handy:



<?php
function debug($var) {
echo "<pre>";
print_r($var);
echo "</pre>";
}
?>

It’ll nicely output any array, object or ugly items you need to debug. You could also add your comments like this while debugging a code snippet, so you can easily switch it off and on:



<?php
// some nice working code here
$var = "ok";

//* Here it starts to get confusing, disable me if you please
$blackmagic = true;
// and anything beyond here will be safe */

$othervar = "here it's ok also, so don't disable me";
// more nice working code here
?>

Just remove the first slash (where you have //*) and it will be disabled, add it back and your code will be processed again.


#10 Break the rules when you want to


Of course you don’t need to hear me to be an awesome programmer. We’re just trying to help you. Same thing about other sites and even WP guidelines. You need to adjust the rules to your needs because there’s no point in following other people’s standards when you feel that it just won’t fit to your needs.


For example, one of the recommendations is to order alphabetically your CSS properties. That’s nice in theory, but I just don’t.


I follow the most confusing rule in the world to order them, the box model (starting from margins, borders, paddings then element styling). That’s because I don’t like to lose so much time by ordering rules, hence what is “natural” is just code as it comes to my mind.


You see? The standard is “ordering alphabetically will save you and other people’s time” but for me it would actually be a big waste of time.


So, what do you think?


Do you have any golden rule you want to share? Maybe your own tips? Don’t be shy and share your thoughts using the comments section!





Advertise here with BSA







Source: http://designm.ag/wordpress-2/10-wordpress-code-formatting-optimization-and-performance-tips/

No comments:

Post a Comment

 

The Cash Box Blueprint

Most Reading