Using the Theme API in plugins

The theme API can be used from a plugin, this section will provide information on how to use it. As example, first create a folder and name it for example “td-api-plugin”, inside the folder create a php file using the same name:

td_api_plugin_structure

Edit the file and add the following code:

<?php
/*
Plugin Name: td-api-plugin
Plugin URI: http://tagdiv.com
Description: tagDiv API plugin
Author: tagDiv
Version: 1.0
Author URI: http://tagdiv.com
*/
class td_api_plugin {
    var $plugin_url = '';
    var $plugin_path = '';
    function __construct()
    {
        $this->plugin_url = plugins_url('', __FILE__); // path used for elements like images, css, etc which are available on end user
        $this->plugin_path = dirname(__FILE__); // used for internal (server side) files

        add_action('td_global_after', array($this, 'hook_td_global_after')); // hook used to add or modify items via Api
    }
    function hook_td_global_after() {

//add the api code inside this function

    }
}

new td_api_plugin();

Next you have to replace the //add the api code inside this function line with the API code you want to use, you can find information and examples on the code in the other specific sections from this documentation (ex. Header style, Category templates, etc.):

td_api_plugin_new_module_code

There are two variables which are used to define the path: $plugin_url and $plugin_path, bellow you can see an example for a site named http://www.site.com/ and the result each one returns:

  • $this->plugin_url  – http://www.site.com/site/wp-content/plugins/td-api-plugin
  • $this->plugin_path  – D:\xampp\htdocs\site\wp-content\plugins\td-api-plugin

For public content like images or css you have to use $this->plugin_url , for the php files you have to use $this->plugin_path ,  check this example:

// Add a new module
td_api_module::add('td_module_77',
    array (
        'file' => $this->plugin_path . "/modules/td_module_77.php",
        'text' => 'Module 77',
        'img' => $this->plugin_url . '/images/modules/td_module_77.png',
        'used_on_blocks' => array ('td_block_77'),
        'excerpt_title' => 12,
        'excerpt_content' => 25,
        'enabled_on_more_articles_box' => true,
        'enabled_on_loops' => true,
        'uses_columns' => true,                      // if the module uses columns on the page template + loop
        'category_label' => true,
        'class' => 'td_module_wrap td-animation-stack',
    )
);

After you add the code and the eventual files required by it, the plugin should be ready to install, copy the plugin directory inside the ..\wp-content\plugins folder or add it into a zip archive and use the wp-admin area section to install it like any other plugin.