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.
Thank you for the great article. Another candidate for prefixing are PHP constants.
I also started a small collection of standard handles for scripts, styles and image sizes. https://github.com/grappler/wp-standard-handles
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.
I like your recommendation for image size naming.
Fixed link: https://github.com/grappler/wp-standard-handles
Why IS small letter “I” removed from all the comments? 🙂
thanks
https://twitter.com/safety/unsafe_link_warning?unsafe_link=https://umusic.top
Great reference. Thanks for this, J-money. =)
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
Good one. I often forget about that with themes because I use the Theme Mods API, which takes care of that problem for you.
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?
Never mind, I just realized that the Theme Mods API is probably pretty similar to the Settings API in how it stores data.
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.
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
.Actually, if a theme author is properly using
add_theme_page()
, the admin URL will bewp-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.
Great Article. It should be linked in the Theme Review Handbook
Definitely. We’ll see if we can get it up there. Having this info available to both theme authors and reviewers is the goal.
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
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.
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.
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.
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.”
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
I think this stuff sounds more straightforward than it actually is?
Underscores and hyphens have always haunted me!
And what about shortcodces? Shouldn’t these be prefixed?
Themes shouldn’t register shortcodes. That’s plugin territory. But, yes, it would probably be a good idea to prefix them.
Whats your take on prefixes for post/content type and taxonomy names?
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.
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”.
Frameworks, libraries, etc. They’re all the same.
very nice.
goodddd
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?
It doesn’t matter if you’re self-hosting, on ThemeForest, or on WordPress.org, follow the above guideline.
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?
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.
Hey Dragan,
It should be as it was shown above
`themename_`
Please see the following link as well:
https://forums.envato.com/t/new-wordpress-theme-submission-requirement/9869/105?u=stephencronin
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!
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!
Thnx bud, your instructions are valuable to may of us.
Happy New Year ( Sretna Nova pasa 🙂 ) !
Thanks (Hvala) 🙂
Good Article, helped me a lot in understanding importance of prefix in theme review.
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..
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..
What about class functions should these functions be prefixed as well?
No, class methods shouldn’t be prefixed. They’re within the scope of the class and not in the global namespace.
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!
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 usehcytt_
.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!
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.
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!
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.
Hi Justin,
Do we need to prefix customizer sections,panels,controls and settings too?
Thank You.
suppose we have function under a class. should we add prefix before this function which has class name with prefix ?
Functions within a class (i.e., methods) should not be prefixed. They’re limited in scope to that class.
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_”?
Treat the framework as a separate project with its own, unique prefix.
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
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.
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
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.
I followed your advice and started prefixing everything last year.
Recently came through an article that suggested using PHP namespaces instead of prefixing. Do you think it’s a better approach?
Should we also prefix theme’s css classes to avoid conflicts?
Using PHP namespaces is better than prefixing. And, you don’t need to prefix anything that’s namespaced. The only problem with that is WordPress still supports a minimum of PHP 5.2. Namespaces aren’t available until PHP 5.3.
So, you’ll need to make the decision to drop support for PHP 5.2 and gracefully fail for users of your theme who are not on that version.
I’ve personally made the decision to only support PHP 5.3+ in my plugins. I haven’t bumped up the min. version for my themes yet but plan to do so.
Thank you for your insight, Justin.
PHP 5.2 is not an issue for me because I’m already supporting only PHP 5.3+ in my themes.
I have a couple of articles in the past few days about PHP namespaces. So far I love the advantages of using theme. It would make the code so much easier to manage.
I’m hesitant to switch to namespaces is that in 2018 I plan to submit my themes at WordPress.org, ThemeForest, and other market places. And I’m not sure how open theme reviewers are open to using namespaces. What do you think?
Also, I haven’t come across any theme that uses it instead of prefixing. I assumed there must be some major downside to it.
WordPress.org is fine with namespaces over prefixing. I don’t see why any other marketplace would be any different.
The reason you don’t see many themes using namespaces comes down to what I said above about PHP support. Even if a theme author isn’t actively looking to support PHP 5.2, nearly every code example they’ll see supports 5.2. Prefixing is just sort of ingrained into the WP dev community psyche.
Once WP drops that PHP 5.2 support, namespacing will be more commonplace. It’ll take some time, but it’ll happen.
I’m going to switch to namespaces then. Hopefully, other theme authors would follow the suit soon.
If you have time, could you share a link to a WordPress theme or plugin (preferably yours) that I could use as a reference while using namespaces? I want to avoid as many mistakes as possible.
he estado navegando en lÃnea más de 3 horas hoy,
pero nunca encontré ningún artÃculo interesante como el tuyo.
Es Vale bastante lo suficiente para mÃ. En mi opinión, si todos propietarios de sitios web
y bloggers hacen un buen contenido como tú, web a mucho más útil que nunca antes alguno?
Kindly let me reconozca para que I pueda suscribirme.
Gracias. quiero desear sugerir usted some atención-agarrando cosas o consejo .
Quizás usted podrÃa escribir próximo artÃculos referirse a este artÃculo.
Quiero deseo leer aún más cosas aproximadamente eso!
mantener el genial trabajar!
Hello,
thanks for this great article.
I have a quick one regarding this article:
Let’s say my username is `mypreview` and my item (WordPress theme) name is `XXXX` so according to what you guys have mentioned above can we do the prefixing of the methods and class names as follows?
“`mypreview_XXXX“`
Thank you for some other fantastic post. The place else
could anybody get that kind of information in such a perfect method of writing?
I have a presentation next week, and I am on the search for such information.
Many thanks sir, my utmost appreciation for the hard work of
your team, i am a regular visitor to your site indeed, i thought to,
(out of courtsey) provide some suggestion and feedback of
my very own , would be thankful if you could reply or recognize my recommendations to make this website more content focused
.
https://global-alliancewm.com/
Regards.
free webkinz codes 2019
thank you for sharing. what’s next?
Wood furnishings possesses one thing quite natural
about it. There is this sense of comfort, of attribute as well as of sophistication that can be be found in wood furniture.
Hardwood is actually born from the earth. It feeds the fire, degenerates in to
drafts and ashes away. It is actually quite near to the human presence in the world.
May be actually that is why it sounds so much with us.
Might be that is why you still get that hot sensation when you contact an abundant mahogany desk.
thank you for sharing