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();

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.

USEFUL?
We benefit hugely from resources on the web so we decided we should try and give back some of our knowledge and resources to the community by opening up many of our company’s internal notes and libraries through mini sites like this. We hope you find the site helpful.
Please feel free to comment if you can add help to this page or point out issues and solutions you have found, but please note that we do not provide support on this site. If you need help with a problem please use one of the many online forums.

Comments

Your email address will not be published.