Creating a plugin inside a namespace

By using a namespace, everything inside the namespace does not need globally unique naming prefixes, solving clashing issues with other plugins, themes and wordpress itself. Using a namespace is much simpler than using a class for your plugin.

Add all your php files to the namespace

Add this to the top of each file

<?php
namespace MyPluginName;

Every function or class defined in this file will be considered as part of this namespace

WordPress hooks, Shortcodes, etc

You must include your namespace in the definition, e.g.

add_action( 'wp_enqueue_scripts', '\MyPluginName\my_function_name' );
function my_function_name()
{
}

add_shortcode('my_shortcode', '\MyPluginName\my_shortcode_function');
function my_shortcode_function()
{
}

Calling Functions

Functions in a file under the same namespace

You can call it directly

WordPress functions

If you don’t have a function with the same name under your namespace then you can call it directly.

Forcibly specifying that the function is in the global space:

  $post_id = \wp_insert_post();
Functions in another namespace (and calling functions in your plugin from outside the plugin)

You need to specify the namespace:

$Result = \SomeOtherNamespace\function_name();

If you want to define the other namespaces function a being used within this namespace you can use:

use function SomeOtherNamespace\function_name;

//Now your can use that function directly
$Result = function_name();
Functions using the same name in your namespace and also not in any namespace

How a call to function foo() is resolved – calling from inside the namespace:
1) It looks for a function from the current namespace call foo().
2) If that fails it tries to find and call the global function foo().

How a call to function foo() is resolved – calling from outside the namespace:
It tries to find and call the global function foo().

Defines

By default define() defines a constant in the global namespace, even if used in a file that is part of a specific namespace.

To define a constant for use inside a namespace you need to prefix the constant name with the namespace:

define(__NAMESPACE__ . "\MY_CONSTANT_NAME",          24);

//Which is the same as:
define("MyNamespaceName\MY_CONSTANT_NAME",          24);

Use of the define within the namespace doesn’t require the prefex, just the definition does.

Feel free to comment if you can add help to this page or point out issues and solutions you have found. I do not provide support on this site, if you need help with a problem head over to stack overflow.

Comments

Your email address will not be published.