Organize your WordPress Theme in 3 Easy Steps

I make an effort to keep my code clean for two reasons, ease of use and maintainability. It’s far easier to fix bugs or make updates to the code if it’s clean. It will take much more time if six months or a year from now you need to re-examine your code to figure it out, rather than just fixing the issue. I also am a firm believer in the saying “if you’re going to do it, do it right the first time.” and by proxy “make it right”. Every developer sees some “bad code” at some point, sometimes they may have even written it. I feel it’s important to correct wrongs as you see them and improve your own code as you go.

That’s no easy task, but WordPress makes it a little easier when it comes to theme development. Here’s three steps you can take to make your themes a little better than before.

Step One: Proper Template Directories

This is more of a general step you can take, but still useful, and it’s as simple as creating folders to organize your files in. Many developers like to have seperate folders for JavaScript, CSS, and images. These are the folders that I use to keep everything in its place:

  • /theme-directory/css/
  • /theme-directory/images/
  • /theme-directory/js/
  • /theme-directory/includes/

That last one is important. Anything custom that i’m building for the theme, such as a meta box or option page for the admin section of WordPress, would live in this folder. I used to put some front end PHP in there as well, but more on that later.

Step 2: Registering your CSS and JavaScript

WordPress comes with several functions you can use to queue and load your CSS and JavaScript files. You can set a version number for the files, and even tell WordPress that a specific file requires a previously queued file before this one loads (for example, requiring that jQuery is loaded before a jQuery plugin your theme needs gets loaded).

Step 3: Use WordPress Template Files!

WordPress is built around themes and plugins, and it’s really easy to make your theme easy to manage if you use what has been given to you. The best example of this is the function get_template_part(). This function allows for you to split your template files into smaller more manageable blocks of code. For example, you can make a loop.php file that you can use in all of your template files and include it simply by calling get_template_part(“loop”). It’s just that easy! You can use this function to display any file you make in the main template directory, the possibilities are endless.

That’s all there is to it. Check out the following links for more information.

wp_register_script
wp_deregister_script
wp_enqueue_script
wp_register_style
wp_enqueue_style
get_template_part