Try Tuts+ Premium, Get Cash Back!
Quick Tip: Writing Simple Modular Code

Quick Tip: Writing Simple Modular Code

Tutorial Details
  • Program: WordPress
  • Difficulty: Intermediate
  • Estimated Completion Time: 30 Minutes
  • Files required to edit: functions.php (Make a backup, just in case!)

In my last article, we learned a new way to use Bitly URLs in WordPress. In most of these cases we usually edit our functions.php file. Today we’ll learn a new method for how we can keep our functions.php file nice and clean by using a modular approach.

In this tutorial you’ll learn how you can make very simple modular code. It will be simple code, and because it is modular you have to implement it manually. Why use modular code anyway? Basically modular code is a part of your WordPress theme’s files which you can install and uninstall and can work with many themes. So if you change your theme but still want your custom functions with your new theme, this method will come in handy.


Motivation

Initially, it’s likely that you might think to yourself, “why should I bother doing this?”, and, “what good will it do?”. This is what drives away most people from taking up this modular approach, but be patient, the results will be reaped in future. If you develop themes, then you may know this method already but if you are starting out, this trick will help you save time copying and pasting functions again and again.


Example 1

We will be writing a simple function and will see how we can incorporate this file in our theme’s functions.php


Step 1.1

So lets write a new function. This code is in PHP so we’ll be enclosing it the way we usually do for a standard PHP function.

<?php
// Register WordPress 3.0 Menus
add_action( 'init', 'register_my_menus' );
function register_my_menus() {
	register_nav_menus(
		array(
			'primary-menu' => __( 'Primary Menu' ),
			'secondary-menu' => __( 'Secondary Menu' )
		)
	);
}
?>

As you can see this is just a standard function for registering the menus. Copy the above code and paste it into your text editor of choice and save it as my-modular-code.php


Step 1.2

Save this file along with your WordPress theme files, or you can save it in a sub-folder if you like. I would suggest saving this file in a sub-folder, so when you change your theme you can copy the folder with all your custom functions, which will help portability.

Go ahead and open your theme’s functions file, usually named functions.php, and paste this line of code just after the opening PHP tag:

include_once('path/to/my-modular-code.php');

This line of code will access your my-modular-code.php file and will run the code within when this command is executed. This trick helps keep your functions.php file clean and easy to navigate.


Example 2

Let us do a similar example. Assume that you want to add shortcode functionality to your blog. For this we usually tend to copy all the code into our functions.php file, which is not necessarily bad. But as time progresses you will have an overflowing functions file. So to avoid that we’ll use the same modular approach.


Step 2.1

Copy the code below which is simple and straight forward, and save it as my-shortcode.php into the same sub-folder as the previous file.

function bold( $atts, $content = null )
{
	return '<span style="font-weight:bold;">'.$content.'</span>';
}
add_shortcode('bold', 'bold');

The code is very simple and it will just bold the characters when the text is enclosed within [bold][/bold] tags.


Step 2.2 Calling the my-shortcode.php File in functions.php

Now open up your functions.php file and paste the same code as we did in our first example, only replacing the file name:

include_once('path/to/my-shortcode.php');

When the function file reaches this line of code it will go to the my-shortcode.php file and will include all the code which is residing within it!


Conclusion

As we learned earlier, this method helps in keeping our functions file nice and clean. Other than that it will help portability when changing themes. You could easily change your theme without scouring through your old functions file to find your custom shortcodes and snippets. This saves a lot of time and prevents headaches! I remember when I made a theme for my own blog, the functions file reached a whopping 1500 lines, and if you want to find a small bit of code it’s almost certain that you will end up making a mistake.

This is also a good introduction to making a plugin. In other words this is sort of like the simplest plugin you could make. This will help you in understanding and writing your own plugins in future. I hope that it has increased your knowledge. In the next tutorial we’ll use the same modular approach and write a cool Facebook-like widget.

Have fun trying the code and do let us know if you need any kind of assistance, just leave your comments below and we’ll try to help or troubleshoot your problems. Thanks for reading!

Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • Neil

    Is there any kind of performance hit from having several dozen includes and separate files versus keeping them all in the function.php?

    • Michael

      I’d like to know the same. I’m starting to do more of this and I’d like to know I’m on the right path or if I’m screwing myself.

    • http://logic.lv Yuriy

      No

      • qwewq

        wqewqe

    • http://vim.gentle.ro vimishor

      There is a performance downside at any I/O operation. How big that is, depends on the PC/server configuration you are running the code.

      1. If you keep your code in a lot of small files, you will need to load a lot of files just to do simple things and you will end up stressing the HDD.
      2. If you keep a lot of code in a few files, you will stress the memory.

      Ideal is to find a balance between the two points and to find this balance, it is preferable to use a profiler.

      • http://CLUSTERfoo.com Noam Gagliardi

        A good balance would be to group functions that go together.

        For example, the ‘bold’ shortcode function from this example could easily go in the same file as ‘italic’ and ‘all-caps’ shortcode functions, as it’s not likely that you’d want to move one of those without the other.

  • http://www.plan-zero.org Cristopher Ocana

    Nice little article just one comment, according to WordPress Codex:

    instead of “include_once(‘path/to/my-modular-code.php’);”
    it’s better to use “get_template_part(‘path/to/my-modular-code’);”

    • http://www.marcwiest.com Marc

      I think you could be right, but where did you read about it if I may ask?

      • http://www.fightthecurrent.org Nathaniel Schweinberg
        • flickapix

          sorry to correct you guys but get_template_part is for what the name suggests, template files like comments.php etc, to include non template files require_once() should be used,

          if i was loading in template-comments.php it would look like this, assuming its in theme root;

          get_template_part(‘comments’);

          if i was loading a second function file called custom-functions.php then it would look like this;

          require_once( THEMEPATH . ‘/admin/custom-functions.php’);

          obviously the constant and path to file is theme specific,

          • http://wp.envato.com/ Japh Thomson
            Staff

            Good point, Flickapix! Thanks for the reminder there.

            Hopefully people realise that when the Theme Check plugin flags things like using “include”/”include_once” etc. it’s a warning to make sure you know what you’re doing. It’s not necessarily a correction that you are definitely doing the wrong thing.

  • http://channeleaton.com Aaron

    Would the native PHP autoloader also work? I think it would be great to just throw in a new function file and have it automatically load with WP.

  • Wow

    Wow, you learnt how to include a file. This is typical of the level of intelligence of WordPress ‘developers’…

    • http://wp.envato.com/ Japh Thomson
      Staff

      Thanks for your comment, but let’s try to keep things friendly. Everyone has to start somewhere, and why should we not cover the basics every now and then to help get people off the ground?

      • Ayman

        I tend to agree with you Japh.

        Guys, come on, give the author a break!
        There are alot of PHP newbies and new comers out there everyday.

        Well done Bilal. However, I think it’s better to use get_templete_part();

    • Mike McLin

      The most ignorant comment I’ve read this week. Of course, you are on a WordPress tutorial website, so I guess you don’t think too highly of yourself or your own “level of intelligence.”

      • http://CLUSTERfoo.com Noam Gagliardi

        Give him a break; he was clearly born with an innate understanding of PHP programming. To him, the notion of acquiring a skill through practice and study is completely alien.

        I’d like also to advance the point that, regardless of whether “most of us know this”, 90% of wp themes out there don’t use simple techniques like this to make their code more readable and easy to work with.

        @Wow and Aryan: This tip isn’t about how to use includes, you’ve missed the point. It’s about thinking about how to organize you code. Which is clearly not an obvious skill, given what most code looks like. Most functions.php files I’ve seen are a convoluted mess and could use this advice.

  • Pingback: tips | Pearltrees

  • Aryan

    Such tutorials are useless.

    Every php programmer know this.

    • Rich

      Such comments are useless Aryan. Just because you know something doesn’t mean everyone does. There’s always a new generation of developers behind us who can use tips and helpful reminders.

    • Jose Gomez

      this is just a simple guide to style your function.php, don’t be agressive if you already know it, lets be Social!

    • http://wp.envato.com/ Japh Thomson
      Staff

      Perhaps, but what about people who aren’t PHP programmers yet? Have you forgotten that you once weren’t a PHP programmer? ;)

      • Aryan

        Will someone jump into WP development without learing basics of PHP?

        I didn’t say such tutorials shouldn’t be posted. Quick tips usually gives us some nifty hacks or shortcuts to implement, not such a basic tutorial.

        • http://pippinsplugins.com Pippin

          Yes! People jump into WordPress all the time without knowing ANY PHP. I hardly knew any at all when I started. Coding in WordPress is what taught me PHP actually.

  • Seriously

    Coming soon,

    Come on wptuts your better than this!

  • http://www.customicondesign.com/ custom icon design

    I think this is useful to me. even I am not a newbie in php program. I dont agree Aryan’s opinion. at least the auther remain our programmer to keep good program style. that’s it.

  • http://www.paulund.co.uk Paul

    Nice tips I’ve started creating a theme framework using this same technique.

  • Pingback: WordPress Community Roundup for the Week Ending March 3 - Charleston WordPress

  • Chad

    Thanks for your tutorial. I have been a worpdress developer for about a year now. I for one would have appreciated finding this information when I started. I agree with Pippin. I knew little PHP prior to getting started with WordPress. To me its common and a natural progression for someone to go from doing static html/css sites and suddenly jumping to WordPress due to its overwhelming popularity, and learning PHP by the seat of your pants. If you didn’t find the value in a post like this, then why even waste your time commenting on it? There are plenty of more advanced tuts on here that you could gleam some growth from. There is much more someone could learn from this than just how to modularize their functions file. You may not actually know what:

    add_action( ‘init’, ‘register_my_menus’ );

    means and it may lead you to investigating this standard way of initializing within the WordPress framework. All I’m saying is the basics sometimes make it easier for newbies to get a grasp on simple concepts that are often used within the scope of larger tuts, but never explained and just taken as “common knowledge”. Again I thank you for taking the time to create a “basic” tutorial for the great community here!!

  • The Ninja

    Why all the hate? I’ve learned PHP through WordPress aswell, and even do I already knew this, I havn’t been using it for my functions file before. It’s a good step for optimizing your code, and that is what I’m trying to learn now after getting all the functions and such down.

    GJ Author!

  • http://www.onestopgoa.com John

    take a bow Bilal Shaheen for writing this tutorial…awsome

  • http://webindallas.com Jerry Lee

    Thank you for taking the time to write this tut. It takes a lot of time to organize, and create. Not only are there new developers that can use this info, but also older developers that may be new to WordPress or this way of thinking. Being self taught myself, even though I have been at it for over 10 years, I find neat little tidbits all the time through tuts. The thought that any tut is too simple is just vain. I am sure there is a developer out there that could put your knowledge to shame also (Aryan), so ease up. This is the spirit of open source.

  • http://www.lmdwebdev.com AppreciativeNewbie

    I also appreciate the time you have taken to remember us newbies! have only been programming with WP for about 3 mos and PHP for about a year. While I did understand how to do this, I seem to remember a time when I struggled with even the simplest concept. I’m sure that most of us have experienced this except for possibly the 1%ers that were born brilliant. In addition, I find that even the simplest tut sometimes spurs conversation towards additional helpful insights like the above mentioned alternative to “including” files and instead using “get_template_part(‘path/to/my-modular-code’);” Thanks again!

  • Pingback: Writing Simple Modular Code | Everchanging Media

  • http://twitter.com/vbaimas Vasilis Baimas

    For better organization propose to organize functions in subfolders like, “social media”, “secure”, “admin_panel” etc.