Prefix all the things

When building WordPress themes, there’s a rule that sits at the top of the list of rules. It’s something all developers should do out of habit, not as an afterthought.

Prefix everything.

What does it mean to prefix something? Basically, when you create custom functions, classes, and other items in the global namespace, it needs to be unique so that it doesn’t conflict with WordPress, plugins, or other scripts. Therefore, you add a prefix that’s unique to your theme name. If everyone follows this simple rule, it’s rare to see any conflicts. Like rare on the level of seeing a real-life unicorn.

Is it really a simple rule? Yes, and no. There are times to follow the rules and times to break the rules. There’s also a few extra things to cover, so follow along. While I’ll be focusing on themes, this applies directly to plugins as well.

What’s my prefix?

Fortunately, you have a prefix already made available to you, so all the guesswork about what prefix to use is already taken care of. This prefix is your theme slug. Take a look at the folder name you’ve packaged your theme in. That’s your prefix.

Let’s assume you have a theme named “Firefly” with a folder name of firefly. Your theme prefix is firefly_ or firefly-, depending on the circumstance. We’ll get to when to use an underscore or hyphen later.

Wait? What if my theme name has more than one word like “Firefly Browncoats”? That’s simple. You follow the same convention. Your slug becomes firefly_browncoats_ or firefly-browncoats-.

What should be prefixed?

Believe it or not, there are loads of things that need to be prefixed. Function names are the most obvious, but we’re not limited to those. Here’s a list of the most common things that should be prefixed:

  • PHP function names.
  • PHP class names.
  • PHP global variables.
  • Action/Filter hooks.
  • Script handles.
  • Style handles.
  • Image size names.

Don’t assume this list is exhaustive. I’m sure there are things that I’m missing and new things will come in the future. These are just the common items in WordPress themes.

Also, while not technically prefixes, theme textdomains should also match the slug.

How to use prefixes

The simplest way to use a prefix is to add firefly_ (prefix we used above) to the beginning of whatever it is that you’re prefixing. So, if you had a function named do_something_cool(), you’d want to change that to firefly_do_someting_cool(). Sure, it makes the function name longer, but it also makes sure that the function doesn’t conflict with core WordPress, a plugin, or another PHP script running on a user’s site, which would create a nasty fatal error.

Depending on what you’re prefixing, you’ll need to know how to use that prefix. While there aren’t always hard-and-fast rules, if you follow core WordPress coding standards, things get pretty clear. The following is are examples of the various items that you should prefix.

Function names

function firefly_engine_failed()

Class names

class Firefly_Transport_Boat {}

Global variables

global $firefly_passengers;

Action hooks

do_action( ‘firefly_start_engine’ );

Filter hooks

$shutdown = apply_filters( ‘firefly_shutdown’, true );

Script handles

wp_enqueue_script( ‘firefly-vertical’, trailingslashit( get_theme_directory_uri() ) . ‘js/firefly-vertical.js’ );

Style handles

wp_enqueue_style( ‘firefly-paint-job’, trailingslashit( get_theme_directory_uri() ) . ‘css/firefly-paint-job.css’ );

Image size names (Note: Hyphens or underscores acceptable. Just be consistent.)

add_image_size( ‘firefly-large’, 1000, 500 );
add_image_size( ‘firefly_small’, 200, 200 );

When to break the rules

For every rule there’s an exception, right? Pretty much. There are times when it’s actually better to break the rules.

Pluggable functions immediately come to mind. I almost always advocate for not using pluggable functions for various reasons (we’ll save that discussion for another day). They exist, so we’ll talk about them. When building a child theme, it’s possible that the parent theme developer created some functions that can be overwritten in child themes. In that particular case, you must use the same function name to actually overwrite it.

Third-party script/style handles also offer a unique situation. See, if your theme loads the Genericons font stylesheet and another plugin does the same, you’d only want that file to load once. If both have unique handles, it’ll load twice. The best thing to do in this situation is to not prefix and simply use genericons in this case. Follow the core naming convention of lowercase letters and hyphenating between words in the handle.

Third-party PHP scripts/libraries are something I’d avoid prefixing as well. While it’s possible you could run a string replace in a text editor to add your prefix in, it’d be silly to do this every time you updated the library. Not to mention, if you’re using a version control system, you’re probably just pulling in those changes. In this particular scenario, your theme should do a function_exists() or class_exists() (whichever the case may be) before loading the third-party file.

I’m sure there are other exceptions as well, but these are the big three. Once you’ve learned the rules, it becomes a lot easier to recognize situations where you can or should break them.

A good rule of thumb to code by: When in doubt, prefix.

58 thoughts on “Prefix all the things

    1. I knew I’d forget something. I’l have to add constants to the mix.

      I’ve seen that handles standard. Great work on putting that together.

  1. Thanks for the article!

    Other things to prefix are data stored in the options table using add_option()/update_option(). These are easily overlooked and wreak havoc when plugins/themes collide.

    Eric

    1. Good one. I often forget about that with themes because I use the Theme Mods API, which takes care of that problem for you.

      1. Interesting… I’ve only ever developed plugins so I was not aware of the Theme Mods API. That’s cool!

        [waaaay off topic] Does it make sense to have a Plugin Settings API instead of using the options table or custom tables?

        1. The Theme Mods API is just a wrapper for the Options API, so it’s not much different. It just takes care of the option name in the database and storing all the theme’s options in a single array.

    2. Correct. If theme uses a custom Theme Options page (not Customizer), then it should prefix the slug of admin page, too. Like admin.php?page=prefix-slug.

      1. Actually, if a theme author is properly using add_theme_page(), the admin URL will be wp-admin/themes.php?page=some-page. The chances of that being a problem are slim to none. Very few plugins will add things to the themes/appearance menu. Yeah, utilizing the theme slug there wouldn’t hurt, but I wouldn’t knock a theme for not using it.

        Like I said though: When in doubt, prefix.

    1. Definitely. We’ll see if we can get it up there. Having this info available to both theme authors and reviewers is the goal.

  2. thanks for this great article.

    but i think a suffix is better than prefix.

    a suffix will make it easier to read and differentiate between multiple items. especially if these items are sorted alphabetically.

    e.g.:
    prefix
    —————–
    firefly-paint-job
    firefly_shutdown
    firefly-vertical
    firefly_start_engine
    firefly_passengers

    suffix
    ————–
    paint-job-firefly
    shutdown_firefly
    vertical-firefly
    start_engine_firefly
    passengers_firefly

    1. I agree that a suffix would work just as well, if not better, for some people. However, the WordPress convention would be to prefix, so I think it’s better to go that route for the sake of sticking with the standards.

  3. This was great. I have always wondered when to use underscores and when to use hyphens. Although it’s not the most critical aspect, I like your recommendation to just follow WP convention.

    1. That could make a post in and of itself. I’m not sure if some of the WP conventions are even laid out anywhere. We just do them because that’s how core does them.

  4. Big like! I’ve been using this technique and I will keep using it. Thanks a lot.
    And should you correct the sentence mentioned? πŸ˜‰

    “The following is are examples of the various items that you should prefix.”

  5. Even if you write non PHP 5.2 compatible code, and are using namespaces, you still have to prefix action and filter hooks. Just a gotcha.
    Also nonces are a candidate for prefixing

    1. Themes shouldn’t register shortcodes. That’s plugin territory. But, yes, it would probably be a good idea to prefix them.

    1. No, post types and taxonomies should never really be prefixed with the plugin slug. Well, mostly never. If a user is attempting to use two separate forum plugins, for example, they simply should not be doing that.

      Anyway, I’ve written an article on post type standards. And, here’s the community GitHub repo for those standards.

  6. What’s your take on Theme Frameworks or theme shops having multiple themes? Do they come under the “Libraries” rule too?

    Sure, having a varied prefix – per theme – for images and script/style handlers would still make sense in this case. But it would be impractical to maintain multiple variations of function names, classes, and “framework hooks”.

  7. Thnx for the info bud. Question , is using theme name prefix a must for TF themes?
    It kinda makes no sense to me if you are creating base theme for all future ones or you using some theme framework .

    I prefix by organisation name , for example if I were to develop base theme for themereview I would use something like

    trw_ or threv_

    as a prefix. You think this would be an issue on TF?

  8. OK , but can you please try to be more specific. The prefix should be used and that is clear without anyone saying so , but why is it a must to use theme name as a prefix?

    According TF submission guidelines
    http://prntscr.com/9c6vst

    it is clear that we must use specific prefix but nowhere does it say that we must use the theme name. Or am I missing something here?

    1. Don’t get me wrong here , I am not pushing an issue but looking for guidelines. We are group of developers (400+) that work with Unyson framework and we are gathering as much info as possible in ref to TF publishing process and placing it in one post. One of our fellow coders got soft-reject and he used those guidelines and prefixes
      http://manual.unyson.io/en/latest/convention/prefixes.html#theme

      So the question above is for all of us not only for me. It is not clear why this

      thename_do_something()

      is so much different from

      thnzx_do_something() or thn_do_something()

      that is basically the confusion that we currently have and it would be great if you could shed some light on that particular issue.

  9. Thnx for the reply Emil. That post confirms that we can in fact use theme framework unique prefix wich was the main question.
    As Stephen says
    themename_
    OR
    frameworkname_ (where framework functions are being used)

    and in further posts down that thread it was said that framework specific prefixes are ok and it would help advise reviewer of those when submitting the theme. Either way I might go with your service once we are ready to go live. Keep up the great work!

    1. You are welcome Dragan. I stepped down as partner 5 months ago and joined Envato.

      Justin and Sakin are here for you

      P. S. When TF reviews a theme this post is always use as reference.

      Happy New Year!

  10. I could’t understand this issue(*Third party scripts/ styles don’t need to be prefixed to avoid double loading.*) in my theme plz help me..

  11. I did clear it but could’t understand this properly(*Third party scripts/ styles don’t need to be prefixed to avoid double loading.*) in my theme plz help me..

    1. No, class methods shouldn’t be prefixed. They’re within the scope of the class and not in the global namespace.

  12. Hi,

    I have important question. I’m developing a theme for ThemeForest.
    I’m using prefix “hc_” but reviewer (only 1 or 3 reviwers) asking me to use the full theme name “y_the_theme”.

    But this is not a good thing to do for multiple reasons:

    1. X Theme is a theme with 150.000+ clients and use prefix “x_”. If a theme famous like this one use a short prefix like this without any conflict problem, my theme will never have conflict problems. Same thing for Visual Composer, a plugin with 1.0000.000+ active installation, and use prefix “vc_”. This is a fact.

    2. Change prefix on a theme complex and big like the my one require I alter and maybe create again all demos of 700+ pages and anyway alter prefix require to check everything again. The bugs probability increase.

    3. This is the most important. Using a prefix of 11 letters instead of 3 create a big downgrade of readability of the code, you will see a everywhere y_the_theme also for small vars and functions. It will also cause a big downgrade of productivity, unacceptable for me, due customize the theme via code require 11x more time everytime a user must write a function or other codes that are prefixed. My theme is like X and a big part is dedicated to customization via code. You can immaginate digit every time 11 letters (also if there are IDE with autocomplete) is a nonsense thing to do. This is a fact.

    So there are facts and evidence that use “hc_” prefix is not a problem at all, and there are facts and evidence that use a too long prefix is not a good thing.

    Sure I can use something like “hcy_” or “y_theme” but for point 1 and 2 there are no reasons to do this.

    Do you agree?

    Thank you!

    1. First, I want to say “Y The Theme” is kind of a silly name. For one, “theme” shouldn’t be in your theme name. We already know that it’s a theme. It’s redundant. But, “Y The” is even worse. Come up with a better theme name. Now, on to your questions.

      1) y_the_theme isn’t necessary. You can shorten that up. However, two-letter prefixes are not ideal and will absolutely conflict at some point with something. And, I won’t bother repeating the people jumping off the bridge analogy here.

      2) First, 700+ pages of demos? Dafuq? πŸ™‚

      Sounds like you need to use WordPress multisite to handle your demo system. Upload your theme one time. The changes happen on all your demos.

      3) I agree that y_the_theme is a crap prefix. Going down to a two-letter prefix is not the answer. If I were to give a hard rule, I’d say at minimum, a three-letter prefix, while not ideal, is much more preferrable. A minimum of four letters is even better.

      What is hc anyway? Your company name? Combine the two and use hcytt_.

      1. Hi,

        I used that name due my theme have similar goals to X The Theme (https://themeforest.net/item/x-the-theme/5871901) so I think that name can communicate better that these two products have similar features. HC stay for Hybrid Composer, the main feature of the theme (http://wordpress.framework-y.com/).

        I’m already using multisite for sure πŸ™‚ But problem is that the contents of every page use the composer components with hc_, but I can manage in some way.

        hc_ is short, I agree, but x and vc (for me) proves beyond any doubt, for sure, that there will not be conflicts problems if my function have long names like hc_get_arr_img, considering also that 99% of user will install less than 10 plugins, the conflict probability is almost zero I think, sure can happen that 1 user to 1000 have a conflict but alter all the theme for a small percentage like this for me is not necessary, and if happen there is always the support that can update the function name in seconds.

        Thank you for the detailed answer, for me the most important thing was the possibility to use a 3-4 chars name instead of y_the_theme and this is ok also for you. I will manage in this way with hcy_ maybe.

        Thank you!

        1. Basically, it sounds like you want to borrow from two well-known brands in the WP ecosystem — X and Hybrid — with your naming. You really should come up with a unique name for your products. Let your product stand on its own.

          It’ll help you greatly with your prefixing issue.

  13. Hello, thanks for this great article.
    I just want to know if I can use camel-case, for example, $pinetree_page_setting -> $pinetreePageSetting, will this be allowed by ThemeForest?

    Off course I will use $pinetree_page_setting, but I am just so curious :p

    Thank you!

    1. I can’t say what is or is not allowed by ThemeForest because I don’t work there. However, I don’t see any reason it wouldn’t be allowed.

      I do recommend against camel-casing though because it’s non-standard in the WP community and the larger PHP community. For JavaScript though, the opposite is true.

    1. Functions within a class (i.e., methods) should not be prefixed. They’re limited in scope to that class.

  14. What about theme framework development? A theme framework may add its own image sizes, post meta, etc. How should we prefix those?

    1. Read current theme name, and use prefix “themename_”?

    2. Or use prefix “frameworkname_”?

  15. Guys, the concept is preventing any possible conflicts in names. While one theme at the moment can be activated, you can use your company prefix for your class names and function. Don’t waste your time with others personal preferences. Just follow the logic.

    Good luck

    1. Only one theme can be activated, but an unlimited number of plugins can be activated. If you’re just building themes, sure, your company name alone might make for an OK prefix.

      Once you have a few dozen plugins and some themes, any number of which can be activated at once, it’s best to namespace based on the project. Not to mention, the project name will make a lot more sense for third-party integration.

      Save yourself some time and namespace based on your project to start with. Even if you never plan on building more than one theme, you never know what the future holds.

  16. Hi Justin,

    Do we have to prefix customizer sections, panels, controls and settings?
    I see that you don’t do it inside your themes (e.g. Extant), neither does Twentyseventeen. However Storefront does it.

    Thanks

    1. I replied to your email, but I wanted to cover this here too because it’s a good question.

      Essentially, it is good practice to namespace/prefix anything unique to your theme. Customizer sections and panels are not likely to have conflicts (unless you just have tons and tons of them). However, it never hurts to play it safe.

      As for settings, you shouldn’t need to prefix those if you’re using theme mods because the database option would automatically get prefixed by WP.

Leave a Reply

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