How to create your own WordPress functionality plugin

109 Comments

A common, yet unfortunate practice in the WordPress community involves filling theme functions.php files with tweaks and functionality that is key to a site. The reason this is a bad idea, in short, is that it will tie your critical site functionality to a theme that will eventually change. Good news, though: there is a much better, smarter alternative. It’s called a functionality plugin.

We’re going to create a very simple, very specific functionality plugin that you can (hopefully) use to replace your theme’s functions.php file. After all, the poor guy deserves a break, doesn’t he?

What (and why) is a functionality plugin?

First of all, the thing to realize with plugins is that, for all intents and purposes, they behave no differently than your theme’s functions.php file. I won’t say there are no differences, of course, but a plugin file should not be treated as something foreign and strange. If you’ve edited your functions.php file — even if you’ve just edited it by dropping in PHP that you found searching online — then you are familiar enough to manage your own plugins.

You can think of it as a portable functions.php file that you can take with you when you change themes.

Having said that, when I refer to a functionality plugin, I’m talking about a certain type of plugin intended to belong to a specific website. You can think of it as a portable functions.php file that you can take with you when you change themes.

Functionality plugins should contain all of the code that is important for the necessary structure and functionality of your website. By creating a plugin specifically for your website you have the ability of taking the most important parts of your site with you from theme to theme.

Let’s look at a couple of examples. One common thing often added to functions.php files is a register_taxonomy function. This sort of function will create a custom taxonomy (like categories or tags, but defined by you) to allow you to organize your content further. This is what it would look like:

function people_init() {
 register_taxonomy(
    'people',
    'post',
    array(
      'label' => __('People'),
      'sort' => true,
      'args' => array('orderby' => 'term_order'),
      'rewrite' => array('slug' => 'profiles'),
    )
  );
}add_action( 'init', 'people_init' );

If we include this in our WordPress theme’s functions.php file we may run into a surprise when (not if) we change our theme in the future and don’t see our custom taxonomy on the Dashboard anymore. In order to maintain our taxonomy we would have to scour the functions.php file before the theme change to make sure we didn’t miss anything important.

Or, and this is what I recommend, we could create a plugin named after our site and put the function in there. Then we can change themes freely, knowing that our most important, core functionality is preserved safely in a plugin. I call these special types of plugins functionality plugins.

What belongs in a functionality plugin?

To decide what belongs in a functions.php file and what belongs in a functionality plugin, think long term. Rather than thinking about how your website will look and behave this week, think about how it will look and behave five years from now. With few exceptions, I bet all of our sites will have new and upgraded themes in five years’ time.

For every item we might instinctively want to add to our functions.php file, we should stop and consider whether our site will depend on that functionality in five years or not. Consider the following list of functions, for example:

  1. register_post_type() and register_taxonomy(), for creating a custom content type and related taxonomy.
  2. add_shortcode(), to create a shortcode for publishing certain kinds of content more easily.
  3. add_theme_support( 'post-thumbnails' ) and add_image_size(), to enable post thumbnails and set a certain size.

Let’s take the first example, register_post_type() and register_taxonomy(). In five years will you still want these types of content available to you on the Dashboard and on your site? Of course you will, that’s your site’s content! Your content and how you can access it shouldn’t be determined by the particular theme you’ve chosen. These, and others like it, should be included in a functionality plugin, not your functions.php file.

In the second example, add_shortcode(), we’re adding a way to drop in potentially complex code into our content. There’s a rule of thumb I have for determining what belongs in a plugin: if it modifies or interacts with content it belongs in a plugin. In this case we’re quite literally creating content, and if this function is missing our content will display in the raw shortcode format. In this case as well, it belongs in a functionality plugin.

For more on shortcodes and their use in WordPress themes, see Justin Tadlock’s recent post.

Finally, the third item add_theme_support( 'post-thumbnails' ) and add_image_size() add a post thumbnail and particular size to your site. This is one case that I would say is debatable, since post thumbnails, and in particular sizes, may depend largely on the particular display of your site. In my own case I define post thumbnails in a plugin, but I could see the argument for including them in theme files instead. So, in this case: it depends.

What belongs in functions.php?

Your theme’s functions.php file is for any functions or declarations that are necessary for your theme’s appearance. As long as what you’ve added there don’t effect your content in any way, you should be just fine.

There are a number of examples of functions best kept in your theme’s functions.php file:

  1. registern_nav_menus()
  2. register_sidebar()
  3. wp_enqueue_script() and wp_enqueue_style()

The register_nav_menus() is appropriately placed in a theme’s functions.php file, since the placement of the navigation menus themselves depend on the given theme you are using. Keeping this function in a plugin would give you menu placement options on the Dashboard that wouldn’t actually display anywhere in your theme.

register_sidebar() should also stay in your functions.php file, since once again registering sidebars in a plugin could mean you have active plugins on the Dashboard that don’t actually show up anywhere on your site. That would be pretty silly.

wp_enqueue_script() and wp_enqueue_style() are both similar, and I would say depend on the situation. If you are creating a child theme they belong in functions.php. If you are adding them for another purpose (modifying the WordPress admin bar, for instance) then a plugin would likely be more appropriate. As in our earlier examples, this third example requires a bit of context to be sure whether it belongs in functions.php or a plugin.

How to create your first functionality plugin

Creating a functionality plugin is easy, particularly if you understand it as an extension of your functions.php file. You’ll want to start with a plugin file with the appropriate comment header, like this:

/*
Plugin Name: Your Site's Functionality Plugin
Description: All of the important functionality of your site belongs in this.
Version: 0.1
License: GPL
Author: Your Name
Author URI: yoururl
*/

Save that as a PHP file within its own folder in your site’s plugin directory. I would also recommend maintaining a basic readme.txt file for your own sake. Trust me, you-in-five-years will thank you for starting it today. Document the changes you make to your functionality plugin, as well as what everything does.

If you’d like, download our blank functionality plugin to help you get started.

Now head to your WordPress plugins page and activate your plugin. Congrats, you just activated your own plugin: your own comment-only, functionally empty plugin, but your own plugin nonetheless! It won’t do anything, but the nice part now is that you have a file on your site, a plugin file, that will behave much like you’re used to functions.php behaving. And instead of abusing your functions.php file with code you will need later on, you can use your new functionality plugin.

What goes in our plugin?

Now comes the fun part, where we move over site-vital functions to our plugin. To briefly recap, we’re interested in moving functions that are vital to our site’s operation stuff we will want around when (not if) we change our theme in the future.

Everyone’s functions.php file will be slightly different, as well as what will count as “vital site functionality”. But here’s a table with a handful of functions I’ve seen floating around, and where I think they belong:

Purpose of codeFunctionality pluginfunctions.php
Creating shortcodesAlwaysNever
Adding scripts and stylesDependsDepends
Creating sidebarsNeverAlways
Creating menusNeverAlways
Add post types/taxonomiesAlwaysNever
Add post thumbnailsDependsDepends
Add Google Analytics to footerAlwaysNever
Customize WordPress DashboardAlwaysNever
Change default GravatarAlwaysNever
Add custom profile fieldsAlwaysNever

There are plenty of other examples I could use here (actually, limitless examples) but these should be enough to deliver my point.

Your future creating plugins

Sometimes even the functionality plugin may not provide as much universality as we want. Sometimes it may be better to create our own plugins to create unique functionality in each one. If you’re anything like me, functionality plugins like this will be your first foray into WordPress plugin development. I’m much closer to the beginner side of the spectrum than I am the expert side, but what I’ve learned the past 6 months or so has been driven in large part by working in plugins rather than functions.php.

Next time you are copying and pasting a function from a website, or perhaps you managed to piece together code doing just what you need for your purposes, consider abstracting it, writing yourself some solid documentation on what it does, and turning it into a plugin of its own. Likely this won’t require anything more than moving that function into a plugin file with the appropriate commented header (seen above). By doing this you will have tiny portable pieces of functionality you can enable on sites whenever you need them.

I, for instance, created a few super simple plugins just this month:

  • Admin Bar Hover Intent: This one I’m proud of, because I actually released it into the wild on the plugin directory (something I’ve only done once before). It simply implements jQuery hoverIntent on the dropdowns, requiring a deliberate pause over them before they drop down.
  • Admin Bar Cleanup: Sometimes I create plugins that tweak things to operate just the way I like them. In this case, Admin Bar Cleanup just hides the WordPress search bar from the admin bar for me. I don’t use it on every website of mine, but on a few it’s definitely active.
  • Login Redirect Home: This plugin simply, when active, redirects all login activity back to the home page. I use this one sparingly: only on team P2 blogs, team wikis, and task tracking sites.

Not long ago I would have just added it to my site’s functionality plugin (or worse the functions.php file) and moved on, only to likely re-do the same work later in another project.

But each of these plugins requires less than twenty lines of code. All I did was stop myself from adding functionality to only my own site, and stepped back to consider the usefulness of the functions outside of the current project. If there was use for it, I whipped up a quick plugin file and dropped the code in.

What are your thoughts?

Your turn to speak up. What are your thoughts on functionality plugins? Looking through your theme’s functions.php file, do you see anything which would be better off in a functionality plugin to preserve it for your next theme choice?

109 thoughts on “How to create your own WordPress functionality plugin

  1. Doh! I never thought to do this until now. Thanks for this tip!

    When I designed the new WishList Member site (a child theme of Canvas), the functions.php file grew to a whopping 1,300 lines of code. A plugin would have been much better!

    Now I’ve got to figure out how to retro-fit all my previous WordPress theme customizations with a plugin instead of bloated functions.php files.

    Thanks again.

  2. I’ve been doing this for a while. I have a plugin file named mylocalcust.php which is my “My Local Customizations” plugin. It contains things like custom <meta> tags, javascript loaders for services that don’t merit their own separate plugins, custom content filters, overrides for default WP behaviors, and whatnot.

    Once upon a time, WordPress supported a myhacks.php file, which would automatically load if present. A Functionality Plugin is the modern version of myhacks.

  3. Hi Ryan,
    Completely agree with just about everything that you have mentioned here. Nice work! I started creating a “functionality plugin” for my site a while back. This file has evolved into many “focused” plugins that are only responsible for accomplishing one task. I really like the new setup. If something goes wrong in one of the plugins, I can deactivate the functionality directly from the administration panels without having to edit code. This is really handy!

    To add to the discussion, I would say that widgets are almost always better registered in a plugin rather than a theme and any option that cannot be represented as a theme mod should be added via plugin as well.

  4. I use a mu-plugin to add any custom functionality. I name it something like aaaaaaaa.php to make sure it’ll load before anything else. Utility functions go there (such as generating CPT and taxonomy labels arrays) so that any plugin I write later will always be able to use them.

  5. Excellent tips, especially where you suggest to make a plugin of each functionality snippet! Your article has inspired me to start working on something like this too. Thanks!

  6. This looks so simple, and yet genius. I’m continually looking for improvements in the way I create sites for my clients. Not being too technical myself, I’m reliant on posts like this (and cleverer people like you Ryan) to drive me in the right direction. WordPress perfection still seems a long way off, but at least there’s great coffee on the way. Thanks :)

  7. I am super guilty of telling people to put code into a theme’s functions.php file, for two reasons. It always always exists, and telling people to create a plugin is more complicated than needed.

    However, yes, site-specific custom plugins are useful and the way I always do things myself. I highly recommend this instead of screwing around with the theme. Theme files should only contain things related to the theme and the display of the site, nothing else.

  8. I didn’t think I was ready to write plugins. But I wrote a functionality plugin in about 20 minutes — and it worked! Very well-written and useful post.

    • I agree, it’s a facepalm moment for me too. I’ve made plugins but never thought on using it this way as a backend architecture instead of putting everything in the functions.php. Thanks for the great write up!

  9. I have an off the wall question and you do not have to publish it if you do not want :)
    Q: Is there a way to reverse this and make it use one theme for say 22 domains ?
    I have the same theme on several domains and am trying to save space by hosting it (my preferred theme) on -at / one location and have all the sites pull “that theme” from there with out re-hosting it over and over.
    PS all the sites are on one Hostgator VPS space. ?? any Ideas ? anyone ? and please,do not mention AWS to me in any answers, they are way to expensive & I do not trust them at all !!

    • Why don’t you use WP multisites? (used to be WP-MU before, now it’s included in standard WP version).
      define(‘WP_ALLOW_MULTISITE’, true);
      Read more on codex.wordpress.org/Create_A_Network
      It is also possible later, through use of a plugin such as WordPress MU Domain Mapping, to map individual sites to independent domain names.

  10. Thanks for this great article.

    This begins to address an issue I have had a long-standing problem with: The great selling point of WordPress is (or was) that it separated content from presentation. With the growth in theme frameworks and integrated theme functionality, though, it seems that the community is fragmenting into “Thesis” sites, “Genesis” sites, “Headway” sites, etc. where the theme itself is so inextricably woven into the site, that upgrading becomes an issue, and re-theming is impossible.

    Worse still, when clients come to me for site make-overs, I have to determine if the unfamiliar framework or patchwork of theme functions is too complex to cost-justify the time and effort of redesign. I have spoken to clients who have been turned away by other developers for those very reasons, who now question the decision to use WordPress at all.

    On the other hand, I also understand the framework developers who hesitate to extricate the functions.php because they don’t want their back-end functionality powering every generic theme available.

    This is a great start, and I really look forward to seeing other people’s suggestions and ideas about this.

  11. The upside to this — a BIG one — is that if you network activate your plugin, you can then use the functionality exposed for every site in a multisite network, rather than copying specific functions to the functions.php files for different themes (if you end up using them) of various sites, which is a maintenance nightmare.

  12. WOW! This is one of the moments where you ask yourself something like, How come I didn’t think about this before instead of having a mile long functions file?!

    I totally agree, this is a highly recommended technique. Thank you very much Ryan!

  13. Good post Ryan and I wouldn’t disagree that this is probably a much better way of doing things. But as with most things in life, ideals are just ideals and reality is often far removed from those ideals.

    At Woo, we’ve gone through the process of standardizing as much of our code between different themes as we could. So theoretically we could create a beast of a plugin that contains most of that standardized code, which would solve many of the issues that you mention.

    It does however not solve one problem: supporting that decision across a community of 50k+ users. See, the problem is that as soon as we require an user to download & activate both a theme & a plugin, we’ll be experiencing a massive influx of support questions about issues of a different kind. In the early days, some of our themes required plugins to enable all the functionality and 90% of the “my theme ain’t working” issues were due to that plugin not being installed / activated. This may seem absolutely trivial, but it is the reality as well.

    I reckon there are loads of development best practices that we should all aim to implement, but when it comes to supporting 50k+ users, one needs to be realistic and understand that a support group of that size will rip all your best intentions & practices to shreds.

    So I can’t fault your proposal in one bit, but just based on very early data (when Woo only had a thousand odd users), this wasn’t a viable solution and we’re unlikely to experiment with this in the near future.

    • Adii: Ryan’s solution isn’t the golden bullet, especially given your use case and experience. That doesn’t excuse the current practice. The current situation is untenable.

      Woo is particularly prolific when it comes to shortcodes. Yes, they have good use cases, and they provide a valuable service. But when you provide a shortcode for just about everything under the sun, it hurts bad when a user wants to switch to a different theme. Most of their content is going to be tainted with stuff that just isn’t portable. Shortcodes lock users in.

      This, of course, is a problem. But it’s also a problem we can all solve.

      What if WooThemes released a compatibility plugin for WooThemes shortcodes? It’d be trivial to create and maintain. All it’d need to do is register every shortcode that Canvas does, and gracefully degrade each of them. Drop it in the plugin directory (I’ll personally approve it), and then you can drop a link to that at the bottom of your shortcode page in fine print.

      A user’s content is sacred. It’s hallowed ground. I’m sure your users would appreciate an effort to protect that at all costs.

      If you make it easier for people to leave, they’re more likely to stay.

  14. Thanks for writing about this Ryan, this definitely needs to be more discussed more in the community so theme authors are informed on best practices for theme dev. Themes are designed to be presentational only and not contain data structure/core site functionality, period.

    Falling back to the fact that the functions.php file is always available isn’t a valid excuse anymore, and is just flat out, lazy. Theme companies who have clout in the marktet are in the best position to move WordPress forward with creative solutions in this department. Patches welcome, ya know. Maybe even spark up theme/plugin dependency.

  15. BTW, when trying to decide if something belongs in your theme’s functions.php or in a Functionality Plugin, ask yourself these questions:

    If I switched themes, and this functionality disappeared…
    …would I miss it?
    …would it ‘break’ my site in some way? (I’m using ‘break’ loosely here, subject to interpretation)

    If I installed this theme on somebody else’s site…
    …would they need this?
    …would it expose any of my account info?

    For example: hardcoding your Google Analytics account info into a javascript snippet would expose your account info on somebody else’s site, so it belongs in a plugin.

    There are some things that can be a gray area. For example, a custom function to format your post timestamps a certain way probably would go into the theme. But if you implement it in a way that could carry across to other themes without modification, then you might want to do it in a plugin.

  16. I agree with this 100%!

    It’s funny, you can really notice a shift from the

    Do something without a plugin

    hype to coding towards a sustainable architecture, in recent months.

    Maybe with the adoption of PHP 5.2 as minimum requirement and a more object oriented aproach to WordPress core, one day there will be an easily managable functionality library available in WP?
    Because managing 30+ plugins from the plugin screen in the admin is not very much fun. :(
    Bring in Multisite and you’re really lost after a while.

  17. Seems like I’m one of the few to not entirely agree. Sure, when you want to be able to switch themes easily it’s a good idea to put functionality in plugins. However, when building a site for a client, the theme will be 100% custom build. Everything will be specifically designed and build for this single site. In that case I like it when everything related to that site is in one theme directory. Each and every dependency is a (potential) maintainability issue. Having everything in one place makes it easy to see/remember what depends on what.
    Sure, in a few years time the website might get a redesign/upgrade. But again, for me it’s much easier if everything is in one place instead of having to figure out which plugins are needed/used in the site and which aren’t.

    But maybe this is just my specific way of working with WordPress. I never install and use third party themes so switching themes never happens. In case of a redesign I will just take the present theme and rebuild/improve that one. I might copy paste snippets from other themes (for example from the toolbox theme to stay uptodate with new functionality in wp), but never switch completely.

    • @Matthijs hi,

      just a question , imagine you start your hard coding on already solid base with a set of plugins (third party or your own) and a theme (your own) ready to be adapted to any kind of project… how much time of coding for a customer would you save in a couple of years?

      eg i did my own widget-plugin to manage events in wp 3+ , it took me a couple of days (based on wp calendar widget) , now i charge a customer the functionality of easy event management about 50 euros more and it takes 5 minits of work to add it to a site…

      • @Serge, sorry for the late reply. Your scenario is a valid one. I won’t deny that and I wasn’t trying to in my comment. In the example you give, a widget with event management, we’re talking about something more independent. A little piece of functionality that’s more easily plugged-in and plugged-out (!). What I was thinking about was the real single-use stuff. Maybe the specific menu for a website. Or a little map or something. A certain custom loop.

        Sure I can code every piece of functionality into a plugin. And sometimes, when it’s likely to be re-used, that makes sense. But there are drawbacks. First it takes more time (3 lines of php code directly in a template versus a complete plugin). Second it can make it more difficult to understand what’s going on (instead of looking at those 3 lines of php code in the template itself, you might have to look at the plugin files). Third, it can be unclear what dependencies there are. Maybe the client or someone else using the site has installed, activated and inactivated many more plugins in the years after originally building the site. Now which ones where essential again?

        So I think we do agree that in some/many cases it can make sense to put (reusable) functionality in plugins. But putting things in the function file or even hardcoding them in templates does have it’s advantages as well.

        This discussion reminds me of the one in PHP about the framework/OOP vs old-school procedural coding. In that discussion it’s not black or white either. Sometimes using a big OOP framework makes sense. But other times quickly scripting a few lines of simple php makes more sense.

        • the theme will be 100% custom build

          this sounds nice… sometimes, but sometimes it is so time consuming.

          I do agree with on dependancy point. Just whanted to precise: for me a portable functionality to be put into a plugin starts at around 300 lines, not 3 or 50.

          Here is how i see it :

          i start on a framework that works nice

          then i get about 3-4 plugins i will certainly need

          add a ready to go “bug fix” php into a custom_functions.php of the them i work on

          then i see if i have already plugins (only my plugins) for what the customer wants as principal functionality – example :
          portfolio, crossed catalog for products, front page widget areas or collumns, video publisher, social sharing etc. add this into site structure

          personalisations for my plugins adapted for this particular site ( i leave a lot of php filters in plugins so that they stay flexible from outside)

          then i code about 100 lines php and around 200 lines css for this particular case (mostly small snippets for menus, bylines some functionnality etc)

          if i see that a customer needs something totally new – the number one question is – who else might need this ? case not many peaople (audioforbooks.com) – code goes into functions.php (and i save a copy) , case hundreds++ – into a plugin ( portfolio plugin for a customer made 30+ sells last 25 days, and may be transformed into service catalog with search-replace of notepad++ and a bit of php in an hour)

          But sure i code all possible stuff user needs into one plugin for one given functionality, so that the dependancy is not really touched.

          As you said, this is case by case study. Just i’m trying not to forget to have my snippets handy and well organised to save more time possible.

          cheers,

          PS NIce to meet you !

    • @Matthijs – Glad to see your comment. I was about to comment thinking nobody else had recognized that this idea is not a silver bullet and in-fact your use-case is the perfect example of where this idea may not make the best sense. I’ll elaborate in a general comment below.

  18. This is truly a great article. My thoughts on creating Functionality plugins is that they should be considered part of “WordPress Best Practices”. There is a mountain of published articles people have written showing extensive modification of a theme functions.php file. I’m fairly new to working with WordPress however, not with web application development. My gut instinct has been struggling with the fact that a lot of these articles were geared towards quick mindless hacks.

    When I ventured into using WordPress, the first place I started was working with modifications to the theme. A logical place to start since the look and feel of a site is so important. Sure, enough I made enough heavy modifications to the functions.php file, these changes did not carry over in theme change outs. I was more than a little disappointed in this being “the way to do things” in WordPress.

    Part of the goal in web application ot site development, is the creation of reusable code, right? Makes things easier to manage and allows for flexibility. I’m going to refrain from a long winded rant regarding quick articles being cranked out by a heard of amateur wordpress cattle. This article truly is an excellent one, high quality stuff.

    What’s sad, is that after reading this article. This seems like dead on the money common sense, is just a matter of understanding the architecture of how wordpress is put together. Thank you again for posting this. I myself have been hating this overuse of functions.php modifications. Using plug-ins one is able to maintain separation of reusable custom code vs. theme centric design logic. Great article.

  19. I’m coming from a similar perspective to Matthijs. 90% of the WordPress sites I build are based around custom themes that will in all likelihood not be switched until there’s a major site revamp. This would probably involve either a major shift, very probably including major functionality changes and a new custom theme, or it would be development of the same custom theme.

    I appreciate that because of its beginnings, WP runs a lot of sites where users might just want to “switch” theme. However, most larger clients don’t just apply a new skin to their site when they fancy some different colours!

    That said, I am slowly working out what is best to branch out into a plugin rather than keep in custom theme functions.php. Actually there’s two approaches here: stuff that can go into a parent theme functions.php and stuff that can go into a plugin. Both enable “upgradeability” and portability to some extent.

    The “plugin = behaviour / theme = presentation” dichotomy is a useful rule of thumb, but it’s an ideal, and we all know things gets as ugly when we cling too tightly to ideals as when we lose sight of them!

    • Matthijs and Steve Taylor, I see you point – if it is your site, your code, and ultimately your make-over, then no problem. In my experience that is rarely the case, though. A lot of my work comes from people who were unhappy with their original developer. Sometimes it was work that was started and never finished, other times someone made promises beyond his ability to produce. In either case, I don’t have the luxury of a complete make-over, just a fix-it-and-make-it-work.

      As much as would like to hope and believe that all my customers will stay with me forever, I have to assume that will not be the case. That is why I am looking for coding practices that make it easier on the person who works on the site next, and hope that other will do something similar for me.

      • Nicholas, I wasn’t really thinking in terms of it necessarily being myself who would revamp a client’s site (I moved to WordPress 6 years ago because I wanted an open platform that didn’t bind clients to my development, and necessarily bind me to supporting clients). My point was that my clients don’t really need the ability to easily switch theme, i.e. just change the look-and-feel of their site without really altering anything else. If a client moved to another developer, I’m confident that my theme code has enough logic, comments, and conformance with WP best practices for that developer to get going quickly with whatever changes they needed.

        There’s a catch-22 in your point actually. I’m also get plenty of enquiries from people who have been left in a mess by another developer (I’m lucky enough with my regular clients to not have to take on much of this work). Chances are, the mess includes bad coding. And bad coding is bad coding, whether it’s in a plugin or a theme. Give me good coding in a theme to work with any day over bad coding in plugins.

        Ultimately, I think the “functionality plugin” is a great idea, and I’m certainly moving a little in that direction myself. I’m just wary of the idea being put forward as a dogma, and the attitude of some people in the comments who think that putting functionality in a theme is stupid, lazy, whatever, period – when in fact there are many different scenarios for WP sites, and many different possibilities for good development practices.

        FWIW, my habit is to branch my theme functions.php files into includes which deal discreetly with different aspects, e.g. custom post types, admin interface stuff, metadata, etc. These could easily be slapped into a plugin file. But if that plugin file is unique to the site, is there much difference between it being in a custom theme or in a plugin? I tend to push stuff towards being a plugin if it’s not necessarily unique to a specific site.

        • I agree completely. This idea is very good for many use cases but too easily has the potential to become dogma so consenting voices are needed to give people pause from accepting it on blind faith.

  20. It does make sense to not add all the functionality into your functions.php file. However, instead of creating a seperate plugin for this, I have made it my habbit to create a lib in my theme folder and include those ‘plugin functions’ in functions.php. This way if there ever is going to be a radical update, all that needs to be done is copy the include statements and the appropriate lib folder. No more than three minutes work IMO.

  21. Pingback: Guide to Using Custom Functions Plugins in WordPress : WP Mayor

  22. one good thing about creating a plugin is we do not need to look all over our functions.php file to locate that new function when we need to change or add something new into it.

  23. Putting functionality into a plugin makes total sense and I think it’s the direction I’m going to start going. However, I see where Adii is coming from as well with the concept of having buyers of themes install both a theme and plugin(s) and the potential headaches it could cause.

    That being said, is there any way to build functionality into a theme that 1) checks for the existence of the required plugin and 2) installs the plugin automatically (in the actual plugins folder – not in the theme folder) upon activation of the theme if it does not exist?

  24. Well, after several sites telling me to do this, I figured it was time. I kept all my functions grouped into files, and included them in functions.php. That kept them just as portable. But now I can relocate my functions, and just click to activate a plugin rather than type out the includes line. Sure it like 8 seconds of time saving, but it’s still cool to me!

  25. Pingback: Discoveries of the Week #7 | Bradley Durham Designs

  26. This is a great article and something that I think all WordPress theme developers should read. I work with a number of beginner-level theme developers and will have them read this. The table of plugin vs functions.php is a great help.

    I’ve encountered a few WordPress sites now where the client wants a new theme, and I have to parse through someone else’s (sloppy) functions.php file to find functionality that needs to be transfered to the new theme. Using a functionality plugin, which I do on most sites I build, would make it so much easier for the next developer.

    Also, just a quick couple of commented lines would be a great help to the next guy who has to work with your theme and/or site. So let’s all pay it forward and do it the right way: comments and functionality plugins!

  27. Ok I’m sold. So, next step for me would be adding a menu item to admin, and a settings page for me to put things like the Analytics key (or other services) in.

    Any suggestions for good current tutes that show how to create a plugin settings page?

  28. Pingback: Michael Fields » Plugin Palooza

  29. Wow! This is fantastic! And like others have already said “DOH! Can’t believe I never thought of that!”

    I’ve never written a plugin before but I think I’m gonna give it a shot with this idea. Thank you so much for this solution. I think it’s brilliant! And I”m gonna download your blank framework for it to get started. ;-)

  30. Pingback: Is Your ‘functions.php’ File Tired? | ChurchMag

  31. Pingback: 101 Essential Free WordPress Resources for Building Your WordPress Website | WordPress News at WPMU.org

  32. In many cases I agree, much of the functionality people might store in functions.php should be refactored our into a plugin, but like @Steve Taylor I think this recommendation could easily be mistaken for dogma.

    I think there is a hidden supposition about the use-case for the site, i.e. that this recommendation is about the site that evolves and relies on 3rd party themes not necessarily about the site that is custom built to be client requirements, especially ones for larger companies. This is for people like Ma.tt who switch their theme periodically, not for sites that won’t buy an off-the-shelf theme. For the blogging and smaller online magazine use-case this makes great sense, especially for those that are modifying their own functions.php file. Unfortunately it doesn’t make sense in all cases, and especially not in cases where an agency is retained to build a site for a larger company.

    Case in point I recently refactored a site to move things out of a plugin (which is where I instinctively put the code) and back into functions.php. Why? Version Control. The site used a plugin I wrote with general functional and another plugin that I wrote which had site-specific functionality. Unfortunately to version control the site-specific functionality which included the theme I needed to have everything contained within a single directory, and WordPress’ directory structure does not really support organizing it like would be ideal. Unlike in Drupal (which I otherwise cannot recommend) that has a “/sites/” subdirectory WordPress has no equivalent.

    As I wrote this I tried to think of an easy way to fix this lack of a site-specific directory but frankly I don’t think there is. If a site needs to be version controlled its best to put all the site-specific functionality (vs. generic functionality used by the site) in the theme’s functions.php file. Note that in my site’s case I have a “generic” plugin that does have some of the register_post_type() and register_post_taxonomy() so what I’m really arguing is that approach should be tempered by the use-case.

    Another potential problem with a “Functionality Plugin” (which is a misnomer; doesn’t all plugin code add functionality?) is that it must be turned on or can cause the theme to break. Using a plugin instead of code in functions.php means that the themer needs to add additional check code not to break the site when the plugin is deactivated; putting the code in functions.php eliminates this issue. (Of course storing the plugin in /mu-plugins/ removes this concern, but the article didn’t mention that. Of course @John P. Bloch did mention it in the comments.)

    For those people who have never written a plugin this article is great because it gave them another tool to consider but I think they would do well to learn when and why to use each tool.

    • @Mike, nice one ! this is really needed to be precised – Nothing is dogma here, think first – then do.

      for the plugin active/disabled check in functions.php -

      i use this tip – all checks for display are made on ‘wp_head’ hook or ‘admin_init’ and then the output functions are added where needed (with thesis there is no template system, so the functions are never hard coded into template, nor in the admin area, only hooks/filters are used)

  33. Great article, and great idea, I actually never thought of that. Maybe because I never developped a plugin myself, I usually only work with themes and have to admit that plugin creation seams a little bit “scary” at the begining.
    My technic untill know : I used some includes in the functions.php file file, that would call different functionnalities stored in a “fonction” folder like mycustomposttype.php, or wordpressdrashboardcleanup.php . This way I had clean code, not a 2400 lines functions.php file and was able to maintain each functionnality. It’s similar to Remkus’ lib idea.

    But the plugin idea is great I will definitivly use it as part of my work !

  34. Wow nice idea. I will implement this in the future all the time. Thank You!

    But I have a problem with using this stuff with the Genesis Framework.

    For example if I put the following code in my functions.php file of the theme, it works just fine:
    remove_action('genesis_after_post', 'genesis_do_author_box');
    remove_action('genesis_after_post_content', 'genesis_post_meta');
    remove_action('genesis_post_title', 'genesis_do_post_title');
    remove_action('genesis_before_post_content', 'genesis_post_info');

    But if I put the same code in my own funnctionality-plugin it wont work.

    The strange thing is, that adding actions to genesis hooks works. But removing does not.

    Any idea why this is the case? So there must be a difference between using code in functions.php and in his own plugin, otherwise this behavior would not happen, right?

    Thanks a lot
    Jasmin

    • you may add them like this :

      function my_plugin_add_genesis_functions() {
      remove_action('genesis_after_post', 'genesis_do_author_box');
      remove_action('genesis_after_post_content', 'genesis_post_meta');
      remove_action('genesis_post_title', 'genesis_do_post_title');
      remove_action('genesis_before_post_content', 'genesis_post_info');
      }
      add_action('after_setup_theme','my_plugin_add_genesis_functions',99,0);

      sometimes it is usefull to check from within the plugin if Genesis is installed…

  35. Pingback: WordPress Shortcodes

  36. Interesting approach and very valid. I prefer to use the library solution.

    But I’ve one question, might loading several plugins slow down performances, where you could ask your visitors to load just few optimized files and speed up all the stuffs?

  37. Pingback: Austin Passy site redesign number 4

  38. Pingback: Create a Functionality Plugin Instead of Using Functions.php

  39. Pingback: Create a custom "Download" post type using WordPress

  40. Well written. When thinking about my next site build, I will be pulling a lot of functionality out and into a plugin. It makes the most sense now that I think of it..if I’m adding functionality that will now be key to their site, then it needs to be in a plugin so that they can use it if they choose to change the design/theme later.

    Thanks for writing this post.

  41. Great Article, I started doing this same thing about a year ago. I now have around 20 plugins that I can activate into new site builds, it cuts down my configuration time greatly. Especially when it comes to custom post types, custom taxonomies, or custom meta boxes. I keep 3 plugins that separate each of these into their own plugin, and the development is super fast.

    Even simple little things like: Changing the from email (the email that WordPress uses to send from, on certain hosts it uses the master account email.), It’s only 20 lines of code, but I use it on almost every site I build.

    I wish I would have seen an article like this 2+ years ago when I started working with WordPress. Great work.

    Keep it up!

  42. Ditto x100!

    I realized this issue when working on a recent project. I had to create half a dozen custom post types which each had thousands of content items inside them.

    Halfway through the programming I realized if the user ever wanted to change the theme I would have to strip out all the definitions and login in the functions.php file and transport it to any new theme… BAD IDEA! More importantly, the ENTIRE website was created from these CPT’s. They had almost no Posts or Pages, so 99% of the site’s content was tied to those CPT’s and would disappear if the theme was switched…

    So I went a little farther, and actually created a plugin for each custom post type. This also allows me to re-use those custom post types easily in the future on other websites.

    Great article! I just recently found WpCandy.com and you’re rapidly climbing the charts as a favorite!


    Ellis Benus
    Small Business Web Guru
    [email protected]
    EllisBenus.com

  43. Awesome code/info Ryan, a starter (me) here, it is nice to read “stuff” which make things so much easier. Just a maybe kind of dumb questions here but which goes first, functions.php or a plugin? meaning by this;
    A)
    As soon a site “pops up” at a certain point the functions.php steps in and does his/her job :) but at which moment a plugin steps in (gets the call to be active and forfill his/her roll in this)? before or after the call from the server to functions.php.
    B)
    Is there a difference in weight for the server/database, or is the call equal (functions.php/plugin) and only the code itself the deciding factor for it’s weight if it is about processor/memory load?

    Note: sorry for my poor english, it isn’t my native, and also apologize for the clumsy way of putting the questions here.If all is inappropriate or off-topic please delete my reply.

  44. The article is nice , but in the long run will resolve nothing. the author stated that in “5 years we will thank him” , well – I am all in favor of good coding – but who´s plugin (or theme) is really the same after 5 years ?? so much is changing in a year, new functions, new possibilities …. no one will use the same theme or function in 5 years time . in theory it is nice, butt totally useless in practice. I believe it can make more problems than resolving …

  45. I wish all WP devs and theme creators made sure to adopt this method when responding to their users support questions.

    BTW, would it not be best to have this placed in the mu/ folder?

    • It depends really. I tend to make one — sooner or later — for each site I have on a network. So since they’re site-specific I don’t really want it activated network-wide.

      If it’s a single site installation of WordPres, then yeah I could see adding it there; I tend to just leave it with the rest of the plugins though. Dealer’s choice on that one.

  46. Hello, i have created custom wordpress plugin for rating system, now i want to use that plugin in frontend, i don’t have any idea how to do that,the plug in is just simply insert,update,delete and view data .i have to show my rating system on front, so should i use any function or shortcode to display plugin in front.

  47. Thank you very much. After reading your tutorial I am able to create plugins for wordpress.

    After developing some little plugins with short codes, right now i am able to develop more complicated plug ins.

    Thanks again for your tutorial.

    Regards
    Hafeez

  48. Pingback: WordPress: The Best of 2011 and Future Predictions | Wptuts+

    • I definitely think it helps protect against theme lockdown. The trouble is many commercial theme authors don’t yet offer these sorts of plugins yet, so it’s still a rough spot for WordPress theme consumers.

  49. Pingback: Thesis Theme Review: Why I Give it 3 out of 5

  50. I’m afraid I am simply not seeing the advantage of using a plugin for this over using a child theme – except for some very special cases, like post types, perhaps (though post-type plugins are now everywhere).

    (Was this written before child themes became available?)
    https://codex.wordpress.org/Child_Themes

    I’m always going to have a child theme anyway, so as not to be affected by updates of the theme breaking my functions.php and style.css files, and a simple name change in the style.css file can assign the same stuff to any other theme. So, what’s the point of the plugin except for very special cases where extreme portability and broad application is involved?

    Terry

    (Note – Don’t EVER mess with the theme’s functions.php or style.css files, folks. These child theme files are your own and merge with theirs. No fear of updates wiping out your work.)

  51. Pingback: MSP WordPress #21 Plugin Intro Summary | Minneapolis-St Paul Wordpress User Group

  52. Pingback: WordPress Week: Resources for WordPress Plugin Developers | Web Hosting Blog at ASO

  53. Pingback: Professional WordPress Development Resources for 2012 | kevinleary.net

  54. Pingback: Don’t fork your theme, flex it with “is_plugin_active” conditional | Digging into WordPress

  55. Pingback: Don’t fork your theme, flex it with “is_plugin_active” conditional

  56. This is just a amazing post and blank download is another thing to look for…i am new…i was looking for a post like this…thanks really for the detailed saying about WordPress plugin approval..

  57. Pingback: WordPress Multisite: Practical Functions And Methods | Smashing WordPress

  58. Pingback: Functions: in Theme’s functions.php or in a Functionality Plugin? | PluginBuddy

  59. Pingback: The Practical Guide to Multiple Relationships Between Posts in WordPress | Bitmag

  60. I’ve developed both plugins and themes but somehow I never made the jump to create functionality plugins. You can guarantee that I will be adopting this idea on future updates/builds!

  61. Why is it that still so many people don’t use functionality plugins? The last month I’ve sent 3 people to this post and the amount of people over the last year? Who knows!

    You should add a small update on making your plugin a mu-plugin, after a re-read after so long I think it would be a good addition to the article.

  62. I actually created my own functionality plugin long before I read this post. Nevertheless, it could be a good idea if there’s a plugin where you can just access the settings page, input each and individual function (of course you need to have a name describing the functions) and there’s an ability (still in the settings page) to toggle on/off the functions you’ve created — like activating and deactivating each function.

  63. Just moved a lot of code from functions.php to my newly created functionality plugin file and looks great on the plugins screen with my name on it.

    I’ve had this on my mind for a long time but your article was what put me into action. I especially like the fact that you took the trouble of explaining what can and should be moved to a plugin and why. Thank you!

  64. Pingback: How to Remove Menus From the WordPress Dashboard - WPMU.org

  65. Pingback: Show File Size Information On Attachment Screen - Maor Chasen

  66. Pingback: Simplifying 'My Sites' toolbar menu in WordPress multisite / WP Journo: WordPress & Journalism

  67. Thanks for the tutorial. I noticed you’ve recommended wp_enqueue_style be added to functions.php. I have a CSS file I added styles for certain widgets and plugins throughout my site that I have loaded from the functionality plugin.
    I realize loading multiple stylesheets isn’t good, but is this wrong to do in this situation?

  68. Awesome stuff, defiantly will try it out. I love keeping thing organized and abstract as much as possible. Thanks to @kovshenin for bringing me here:) @drehere

  69. Pingback: Where should I put code from the tutorials? | Event Organiser

Leave a Reply

Please note that WPCandy is a moderated community.

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>