{eac}Doojigger Using Doojigger

Using the methods, filters, and actions provided by {eac}Doojigger.

Document Header

Homepage:https://eacDoojigger.earthasylum.com/ Author:EarthAsylum Consulting Last Updated:12-Apr-2023 Contributors:Kevin Burkholder Requires {eac}Doojigger:2.2

Description

{eac}Doojigger provides many useful methods and hooks which can be accessed from your custom plugins or extensions, as well as from your theme functions or any code in WordPress.

Method Access

Public methods in eacDoojigger.class.php (including abstract classes) may be accessed by using the global eacDoojigger() function.

eacDoojigger()->{methodName}(...$arguments);

From within your derivative plugin, simply use $this and from within your extensions, use $this->plugin *.

$this->{methodName}(...$arguments);
$this->plugin->{methodName}(...$arguments);

For example, to write an entry to the debugging log...

eacDoojigger()->logDebug( $myVariable, 'Logging myVariable' );
$this->logDebug( $myVariable, 'Logging myVariable' );
$this->plugin->logDebug( $myVariable, 'Logging myVariable' );

To access a plugin option...

eacDoojigger()->get_option( 'my_option_name' );
$this->get_option( 'my_option_name' );
$this->plugin->get_option( 'my_option_name' );

To invoke a plugin action...

eacDoojigger()->do_action( 'my_action_name', $arg1, $arg2, ... );
$this->do_action( 'my_action_name', $arg1, $arg2, ... );
$this->plugin->do_action( 'my_action_name', $arg1, $arg2, ... );

To invoke a method in a plugin extension, use callMethod()...

eacDoojigger()->callMethod( [ {extensionName}, {extensionMethodName} ], ...$arguments )
$this->callMethod( [ {extensionName}, {extensionMethodName} ], ...$arguments )
$this->plugin->callMethod( [ {extensionName}, {extensionMethodName} ], ...$arguments )

* Version 2.0.1 of {eac}Doojigger...

  • Removed some method calling restrictions in extensions so that $this->plugin is no longer necessary as long as the method name is unique. Extensions can now simply use $this->{methodName}(...$arguments); to access eacDoojigger.class.php methods.

  • Invoking methods in extensions may be done by accessing the extension directly (by class name) via $this->{extension_name}->{methodName}(...$arguments);. For example, if you have an extension class named 'myAwesomeExtension', you may invoke its public methods using:

    eacDoojigger()->myAwesomeExtension->{methodName}(...$arguments);
    $this->myAwesomeExtension->{methodName}(...$arguments);

Filters and Shortcodes

{eac}Doojigger (and derivatives) provides a front-end filter and a shortcode that gives access to (nearly) all public methods in the plugin and extensions, WordPress options, and blog info.

The filter and shortcode name is the plugin class name ('eacDoojigger'). Arguments include:

  • method='{methodName}' or method='{extension.methodName}'
  • option='{optionName}'
  • bloginfo='{bloginfoName}'
  • args='...', to pass a list of arguments/values.
  • default='...', to set a default value.
  • index='...', to index an item from an array returned by the called method.

Filter Examples:

\apply_filters('eacDoojigger', null, [ method='getVariable' args='session_manager' ]);  //  expecting session manager stored variable
\apply_filters('eacDoojigger', null, [ method='session.sessionId' ]);                   //  expecting session id from session extension
\apply_filters('eacDoojigger', null, [ method='_SERVER' args='server_name' ]);          //  expecting server name from $_SERVER
\apply_filters('eacDoojigger', null, [ method='getPluginValue' args='PluginSlug' ]);    //  expecting plugin slug
\apply_filters('eacDoojigger', null, [ option='siteEnvironment' ]);                     //  expecting siteEnvironment
\apply_filters('eacDoojigger', null, [ option='blogdescription' ]);                     //  expecting WordPress blogdescription
\apply_filters('eacDoojigger', null, [ option='woocommerce_cybersource_credit_card_settings' index='description' default='not installed' ]);    //  expecting cybersource description
\apply_filters('eacDoojigger', null, [ bloginfo='name' ]);                              //  expecting WordPress Site Title

Shortcode Examples:

['eacDoojigger' method='getVariable' args='session_manager']    //  expecting session manager stored variable
['eacDoojigger' method='session.sessionId']                     //  expecting session id from session extension
['eacDoojigger' method='_SERVER' args='server_name']            //  expecting server name from $_SERVER
['eacDoojigger' method='getPluginValue' args='PluginSlug']      //  expecting plugin slug
['eacDoojigger' option='siteEnvironment']                       //  expecting siteEnvironment
['eacDoojigger' option='blogdescription']                       //  expecting WordPress blogdescription
['eacDoojigger' option='woocommerce_cybersource_credit_card_settings' index='description' default='not installed']  //  expecting cybersource description
['eacDoojigger' bloginfo='name' ]                               //  expecting WordPress Site Title

Filters, Options, and Transients

When using class methods to access filters and actions, options, and transients, all names are prefixed with the plugin name ('eacDoojigger_*). These functions are extended wrappers around WordPress methods...

  • $this->add_filter(...) rather than add_filter(...)
  • $this->add_option(...) rather than add_option(...)
  • $this->add_network_option(...) rather than add_network_option(...)
  • $this->add_site_option(...) rather than add_site_option(...)
  • $this->set_transient(...) rather than set_transient(...)
  • $this->set_site_transient(...) rather than set_site_transient(...)

See the Multi-Site Network section for other important differences.

Table Names

For custom table names, use $this->prefixTableName('my_table_name') to ensure uniqueness of your table name(s). This will prefixed your table name with the lower-case plugin name ('eacdoojigger_*).

Front-end, Back-end, Network Determination

In WordPress, ajax requests always return true for is_admin() and false for is_network_admin(). {eac}Doojigger digs a little deeper and returns the correct response for $this->is_admin() and $this->is_network_admin(). It also sets static variables to make repeated checks faster as well as including a few additional methods...

Static variable / method Value / response
static::CONTEXT_IS_BACKEND Set to true when request is for/from an administrator (backend) page
static::CONTEXT_IS_FRONTEND Set to true when request is not for/from an administrator (backend) page
static::CONTEXT_IS_NETWORK Set to true when request is for/from a network administrator page
$this->is_backend() Returns static::CONTEXT_IS_BACKEND
$this->is_frontend() Returns static::CONTEXT_IS_FRONTEND
$this->is_admin() Set to static::CONTEXT_IS_BACKEND on load, can be overriden
$this->is_network_admin() Set to static::CONTEXT_IS_NETWORK on load, can be overriden
Top
How To...

Table of Contents

Clone an {eac}Doojigger Extension

Let's say you want to use the session manager included with {eac}Doojigger as an extension to your own plugin (myAwesomePlugin).

Create session_manager.extension.class.php in your myAwesomePlugin Extensions folder:

namespace myAwesomeNamespace\Extensions;

if ( class_exists('\EarthAsylumConsulting\Extensions\session_extension') )
{
    return new \EarthAsylumConsulting\Extensions\session_extension($this);
}

This works for extensions included with {eac}Doojiger but what about extension plugins? Let's try eacMetaPixel to add Facebook tracking to your plugin...

(almost the same but the auto-loader may not know where to find the extension if it hasn't been loaded yet.)

Create metapixel.extension.php in your myAwesomePlugin Extensions folder:

namespace myAwesomeNamespace\Extensions;

if ( class_exists('\EarthAsylumConsulting\Extensions\metapixel_extension') )
{
    return new metapixel_extension($this);
}
if ( file_exists(WP_PLUGIN_DIR.'/eacmetapixel/Extensions/metapixel.extension.php') )
{
    return require(WP_PLUGIN_DIR.'/eacmetapixel/Extensions/metapixel.extension.php');
}

This will load the metapixel extension, if it is installed, whether or not it is activated.

In both, the extension will be loaded by and will extend your plugin. Extension settings will be added to your options page and those settings will be stored with your plugin settings, prefixed with your plugin name.



Using administrator option field methods

Creating custom post types or taxonomies?

There are several methods used by {eac}Doojigger to create the administrator options screens. These methods may also be used outside of the plugin settings page for which they were created.

Note: These examples should only be used when on your custom screen. You can ensure that by checking the current screen id: if (get_current_screen()->id !== 'edit-my-screen-id') return;


A simple example is to first create an array of field definitions similar to the plugin and extension options (see {eac}Doojigger: Administrator Options)...

$myFormOptions =
[
        'registrar_name'        => array(
                            'type'      =>  'text',
                            'label'     =>  'Registrar Name',
                        ),
        'registrar_phone'       => array(
                            'type'      =>  'tel',
                            'label'     =>  'Registrar Telephone',
                        ),
        'registrar_contact'     => array(
                            'type'      =>  'email',
                            'label'     =>  'Registrar Support Email',
                        ),
        'registrar_web'     => array(
                            'type'      =>  'url',
                            'label'     =>  'Registrar Web Address',
                        ),
];

html_input_style()


To incorporate the css style declarations needed for the embedded html, use the html_input_style() method...

add_action( 'admin_enqueue_scripts', array($this->plugin, 'html_input_style') );

html_input_block()


Then, where you want the form fields displayed, add the grid container and each of the fields, including label and input elements, using the html_input_block() method...

echo "<div class='settings-grid-container'>\n";
foreach ($myFormOptions as $optionKey => $optionData)
{
    $optionValue = ?;   // get the current value for the field
    echo $this->plugin->html_input_block($optionKey, $optionData, $optionValue);
}
echo "</div>\n";

html_input_sanitize()


To validate/sanitize these fields when your form is submitted, use the html_input_sanitize() method...

foreach ($myFormOptions as $optionKey => $optionData)
{
    if (array_key_exists($optionKey,$_POST) )
    {
        $value = $this->plugin->html_input_sanitize($_POST[$optionKey], $optionKey, $optionData);
        if ($_POST[$optionKey] == $value)
        {
            // input is valid (passed sanitization), do something with it
        }
        else
        {
            // input is invalid, let the user know
            $this->plugin->add_option_error($optionKey,
                sprintf("%s : The value entered does not meet the criteria for this field.",$optionData['label'])
            );
        }
    }
}

html_input_section()


For a more advanced layout with multiple blocks or sections of input fields...

$myFormSections =
[
    'registrar_contact'     =>
    [
            'registrar_name'        => array(
                                'type'      =>  'text',
                                'label'     =>  'Registrar Name',
                            ),
            'registrar_phone'       => array(
                                'type'      =>  'tel',
                                'label'     =>  'Registrar Telephone',
                            ),
            'registrar_contact'     => array(
                                'type'      =>  'email',
                                'label'     =>  'Registrar Support Email',
                            ),
            'registrar_web'     => array(
                                'type'      =>  'url',
                                'label'     =>  'Registrar Web Address',
                            ),
    ],
    'registration_defaults' =>
    [
        // ...
    ],
    'license_limitations'   =>
    [
        // ...
    ],
];

Add the fields in each section with a section header and fieldset (html_input_section())...

foreach ($myFormSections as $groupName => $myFormOptions)
{
    echo $this->plugin->html_input_section($groupName, $myFormOptions);
    foreach ($myFormOptions as $optionKey => $optionData)
    {
        $optionValue = ?;   // get the current value for the field
        echo $this->plugin->html_input_block($optionKey, $optionData, $optionValue);
    }
    echo "</fieldset>\n";
    echo "</section>\n";
}

Then sanitize the fields from each section using html_input_sanitize() when the form is submitted...

foreach ($myFormSections as $groupName => $myFormOptions)
{
    foreach ($myFormOptions as $optionKey => $optionData)
    {
        if (array_key_exists($optionKey,$_POST) )
        {
            $value = $this->plugin->html_input_sanitize($_POST[$optionKey], $optionKey, $optionData);
            if ($_POST[$optionKey] == $value)
            {
                // input is valid (passed sanitization), do something with it
            }
            else
            {
                // input is invalid, let the user know
                $this->plugin->add_option_error($optionKey,
                    sprintf("%s : The value entered does not meet the criteria for this field.",$optionData['label'])
                );
            }
        }
    }
}

add_option_error()


In order to use the add_option_error() method to display error notices, you must add the admin_notices action...

add_action('admin_notices',array( $this->plugin, 'plugin_admin_notices'), 1 );

The plugin_admin_notices() method will call the WordPress settings_errors() function and add the error notices to the top of the page.


Convert vertical section headers to horizontal tabs


Easily change a long vertical page with multiple input field sections into a tab layout with each section as a tab.

First add an element with a class of 'tab-container' where you want the tabs...

<nav class='tab-container'></nav>

Next add a 'true' boolean to the html_input_style() method...

add_action( 'admin_enqueue_scripts', function()
    {
        $this->plugin->html_input_style(true);
    }
);

This will include the css and javascript needed for tab functionality.

Additionally, you can pass an element selector which will have its visibility style changed to 'visible'.

        $this->plugin->html_input_style(true,'table.form-table');

Screen Shot


These examples where derived from the Software taxonomy custom taxonomy extension used by {eac}SoftwareRegistry.

{eac}SoftwareRegistry Software Product



Using administrator contextual help methods

Taking the examples above and adding contextual help when adding fields is very simple.

First, in your constructor, add something like this to render the help screen.

add_action( 'current_screen',       function($screen)
    {
        if ($screen->id == 'edit-' . 'my-awesome-screen')
        {
            $this->addPluginHelpTab('My Awesome Screen', $content, ['My Awesome Screen','open']);
            $this->plugin_help_render($screen);
        }
    }
);

Then where you render your fields, render the field-level help with html_input_help()

foreach ($myFormSections as $groupName => $myFormOptions)
{
    echo $this->plugin->html_input_section($groupName, $myFormOptions);
    foreach ($myFormOptions as $optionKey => $optionData)
    {
        $this->plugin->html_input_help('My Awesome Screen', $optionKey, $optionData);
        if ($optionData['type'] == 'help') continue;

        $optionValue = ?;   // get the current value for the field
        echo $this->plugin->html_input_block($optionKey, $optionData, $optionValue);
    }
    echo "</fieldset>\n";
    echo "</section>\n";
}

See Providing Contextual Help for more details.



Validate Registration & Licensing

Simple methods for checking the license level of a registered plugin that uses the {eac}SoftwareRegistry Distribution Kit

/**
 * is license L2 (basic) or better
 *
 * @return  bool
 */
public function isBasicLicense(): bool
{
    return $this->isRegistryValue('license', 'L2', 'ge');
}

/**
 * is license L3 (standard) or better
 *
 * @return  bool
 */
public function isStandardLicense(): bool
{
    return $this->isRegistryValue('license', 'L3', 'ge');
}

/**
 * is license L4 (professional) or better
 *
 * @return  bool
 */
public function isProfessionalLicense(): bool
{
    return $this->isRegistryValue('license', 'L4', 'ge');
}

/**
 * is license L5 (enterprise) or better
 *
 * @return  bool
 */
public function isEnterpriseLicense(): bool
{
    return $this->isRegistryValue('license', 'L5', 'ge');
}
Top

    Write a Reply or Comment

    Your email address will not be published.


    You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>