Table of Contents
Table of Content
WordPress plugins based on nnhelpers #
In the following example, we will create a simple, namespaced plugin and add a CSS and JS file to the page.
- create a folder
example
in thewp-content/plugins
folder - in the folder, create a file called
example.php
and add this script:
File: example/example.php
#
<?php
/*
Plugin Name: Example
Plugin URI: https://www.99grad.de
description: Demo-Plugin for WordPress
Version: 1.0
Author: 99grad.de
Author URI: https://www.99grad.de
License: GPL2
*/
namespace My\Example;
if (!defined('ABSPATH')) exit;
add_action( 'nnhelpers_loaded', function () {
\nn\wp::ExtensionManager()->registerExtension( '\My\Example', [
'app' => \My\Example\App::class
]);
});
Things to note:
- Every class in your WordPress plugin will be namespaced. This is one of the main concepts of nnhelper-based-plugins. WordPress almost exclusively uses global function – and so do many plugins. Global functions are predestined to end up in conflicts. This is why nnhelpers follows modern recommendations and uses namespaces.
- There is no real dependency management between Plugins in WordPress. To make sure that all helper-utilities of
nnhelpers
are registered when your plugin is initialized, we are using a workaround withadd_action( 'nnhelpers_loaded' )
. This event is triggered when all classes and methods of nnhelper were fully loaded. - Inside the a
add_action()
-listener we use\nn\wp::ExtensionManager()->registerExtension()
to register the main entry-point (the "app"-class of our plugin)
File: example/Classes/App.php
#
Next, create the entry-point / the "app"-class of your plugin. It should extend \Nng\Nnhelpers\AbstractApp
and have a method named run()
.
This method will be called during the initialization of all plugins. In the following example we are adding a CSS- and JS-file to the page.
<?php
namespace My\Example;
use \Nng\Nnhelpers\AbstractApp;
class App extends AbstractApp
{
/**
* Main method. Called in main plugin-script.
*
* @return void
*/
public function run()
{
\nn\wp::Page()->addCssLibrary('EXT:example/css/style.css');
\nn\wp::Page()->addJsLibrary('EXT:example/js/script.js');
}
}