Use namespace in plugins and themes

Edward Bock
Write better WordPress code
2 min readNov 21, 2020

The official WordPress.org recommendation is to prefix everything. So your functions look like this:

function my_plugin_save_post( $post_id ){
...
}
add_action('save_post', 'my_plugin_save_post');

This is totally ok if your plugin has a tiny scope. But as soon as you start writing more and more functions and extract logic this code will get hard to read.

function my_plugin_extract_data($request){ 
...
}
function my_plugin_sanitize_data($data){
...
}
function my_plugin_save_data($post_id, $data){
...
}
function my_plugin_save_post($post_id){
$data = my_plugin_extract_data($_POST);
$data = my_plugin_sanitize_data($data);
my_plugin_save_data($post_id, $data);
}
add_action('save_post', 'my_plugin_save_post');

This function prefix my_plugin needs to be unique so you don’t run into naming collisions with other plugins, themes or the WordPress core. Finding a unique prefix is hard because there are so many plugins out there. Finding a unique prefix that is also meaningful makes it even worse because in my experience unique and meaningful prefix can get pretty long. A better way to provide a prefix for every function of your plugin or theme script is to use a namespace.

namespace MyPlugin;function extract_data($request){
...
}
function sanitize_data($data){
...
}
function save_data($post_id, $data){
...
}
function save_post($post_id){
$data = extract_data($_POST);
$data = sanitize_data($data);
save_data($post_id, $data);
}
add_action('save_post', '\MyPlugin\save_post');
// or even better
add_action('save_post', __NAMESPACE__.'\save_post');

You still have to make sure that your chosen namespace is unique but within your unique namespace you are free to use short function names as long as they are unique within your own namespace. Finding a unique and meaningful namespace will also lead to pretty long namespaces but that’s no problem because you only have one unique, meaningful and long namespace line on top of your scripts.

Hierarchical namespace

If you are a developer you probably own at least one domain. You can use those for hierarchical namespaces to easily make them (presumably) unique. For example if you would own the domain my-domain.org you could use the following namespaces in your plugin:

namespace MyDomainOrg\MyPlugin;

And for your theme you could use this one:

namespace MyDomainOrg\MyTheme;

Using a namespace instead of function prefix allows you to write much shorter function names and keep the readability of your code.

What’s your way to find prefix or namespace names and what do you think of this suggestion? Leave a comment and I would be happy to discuss with you.

--

--