Click here to Skip to main content
15,881,248 members
Articles / General Programming

How to use the Token Manager plugin for Wordpress

Rate me:
Please Sign up or sign in to vote.
4.89/5 (9 votes)
27 Aug 2012CPOL8 min read 36K   10   3
An article with detailed code examples of creating tokens and assigning them to pages for display thoughout Wordpress using the Token Manager plugin.

Image 1 

Token Manager Article[^]

Introduction

In my last article I introduced a plugin called Token Manager. It is a Wordpress plugin designed to manage HTML, PHP, CSS and JavaScript as tokens that are extremely modular and easy to use. It allows you to package your code into reusable versioned components that can be used in themes, pages, posts, comments, widgets by token name and or parameter. This separation allows you to keep your code clean and access the Wordpress Api, without having to create spaghetti code that is hard to maintain.

Below, I will discuss how to create a workable token, assign it to a Wordpress page and order it for processing. I will also teach you about the general and hidden features of the plugin that you may or may not be familiar with.

If you need instructions for installing the Token Manager, please visit the previous article for a detailed description. For an easy fast installation you can download it through the Wordpress plugin manager and activate it in a matter of seconds.

Creating Token Types

Now that you have a brief understanding of plugin's purpose, lets now introduce some code and create our first simple token. Before creating your first token, make sure you create your token types. Visit the 'Add New Type' page and create some types.

What are token types? 

Token types are categories for separating your tokens and making it easier to understand the token's purpose. This can be named anything you desire, so feel free to be creative. Some examples of token types.

i.e  page, component, control, text, module, widget, third party, test, data, feed, service, etc.

Once you have created your token types, they will appear under the 'Token Types' page, where you can manage them. They will also appear in a dropdown for assigning, when adding a new token.

Image 2 

Creating your First Token

Now lets visit the 'Add New Token' page. Start off by giving your token a name. Keep your token names simple and easy to remember. Assign the token type from the dropdown list you created previously under the token types. I have included a description box, that allows you to describe the purpose of the token for the hover help menus. This is a great feature for team development and gives other developers fast insight on your code. The final thing to do is add some actual code to the token value. The 'Token Value' has four tabs; HTML, PHP, CSS and JS. PHP can be used inline in HTML, CSS and JS too! It will be processed and injected into the tab at runtime. If you would like to use PHP in a tab, simply add <?php //Your Code ?>, except for the actual 'PHP Tab', where it is not required. This allows the code to be more dynamic. I will show you examples of this later in the article.  

For now, lets create a simple copyright token.

Token Name: copyright
Token Type: text
Token Description: Creates a dynamic copyright span element for a Wordpress webpage.

Token Value: HTML Tab
HTML
<span id="copyright" onclick="copyright_onclick();">
  Copyright &copy; 1999 - 
  <?php echo display_current_year(); ?> 
  YourWebsite, All Rights Reserved.
</span>
Token Value: PHP Tab
PHP
function display_current_year()
{
  return date('Y');
}
Token Value: CSS Tab
CSS
#copyright
{
  color: blue;
  font-size: 12px;
} 
Token Value: JS Tab
JavaScript
function copyright_onclick()
{
  alert('The copyright was clicked!');
}

Once complete, click the 'Add Token' button. Your token will be added to the 'Tokens' page for managing.

Image 3 

Notice the different tool icons on this page for managing the token. Starting from left to right.

  1. Up and Down Arrows - For processing the token in a specific order with other tokens.
  2. Edit Token - Allows you to edit the token and create an updated version. 
  3. Description - Shows a description of the token when hovered. 
  4. Statistics - Shows stats of the token when hovered.
  5. Author - Shows the Wordpress author that created the token. 
  6. Token Page Assignment - Allows you to assign the token to be added to a specific Wordpress page or pages.
  7. Token ID - The unique id for the token.
  8. Token Name - The unique name for the token. Notice the brackets around your token '{copyright}'.
  9. Token Type - The token type for the token.
  10. Version History - Allows you to see what version the token is on when hovered. 
  11. Delete Token - Allows you to delete the token from the manager.  

Assigning a Token to a Wordpress Page

In order for our new token to be displayed on our webpage, we must assign it with the token page assignment tool. On the 'Tokens' page, click on the icon that looks like pages. A popup box will appear. Type in a Wordpress page name or id to search for, then click the search button. Once a page is found, assign it by clicking on it, then click the arrow button to move it to the attached pages.

There are also two hidden page assignments in the search:
  1. Frontpage - Assigns the token to be added on the frontpage.
  2. All Pages - Assigns the token to be added to all pages. Be careful using this assignment, resource intensive, when creating many tokens. 

Since our 'copyright' token will most likely be displayed on every page, lets assign it to 'All Pages'. The last and final thing, to get our token to display, add '{copyright}' to our page using the Wordpress page editor or add it to the Wordpress theme files. The text will be replaced at runtime with the processed token value on the assigned page.  

Image 4 

Navigate to the actual page and it should display. It will show a blue 12px copyright message with dynamic current year and an onclick JavaScript message, if you click on the span.  Congrats you have created your first token!

Token Process Order

In this section I will describe the processing order for tokens with the plugin. Tokens are processed in the order you specify on the 'Tokens' page. By using the up and down arrows you can change the processing order of the tokens. The token process order is lowest to highest in that order. This allows you to use token names in other tokens for replacement of things like paths for links, controls, toolbars, widgets, etc. Each individual token is processed on it's own. This allows the token to pass in different parameters and get different results. If the parameters are the same, the token will be cached and replaced with code that was previously processed. Tokens are processed in the following order. 

  1. Page Initialize
  2. Wordpress Initialize
  3. Global Tokens Initialized
  4. Token Manager Page Buffering Initialized
  5. Wordpress Third Party Plugins Initialized
  6. Token Parameters Initialized
  7. Sort Tokens By Process ID ASC
  8. Token Parameters Injected
  9. Token Value PHP, HTML, CSS and JS Initialized
  10. Tokens Cached in Key Array
  11. Token Replace on Buffered Data
  12. Global Token Replace on Buffered Data
  13. Output Wordpress Page

Globals Tokens 

There are a few global tokens built into the Token Manager automatically. They are mostly used for paths, filenames, urls, etc. Globals usually begin with 'REQUEST_'. A list of globals are below with descriptions of what they contain.  

  • REQUEST_HASERRORS - A boolean value of whether the tokens had errors processing.
  • REQUEST_HOST - The URL host for the domain.
  • REQUEST_SCHEME - The scheme for the URL, HTTP or HTTPS.
  • REQUEST_SITEURL - The scheme and host combined for an accurate URL.
  • REQUEST_FULLURL - The full URL without anything parsed.
  • REQUEST_QUERY - The querystring for the URL.
  • REQUEST_URLPATH - The directory or file path for the URL.
  • REQUEST_FULLFILENAME - The URL filename and filext combined.
  • REQUEST_FILENAME - The URL filename.
  • REQUEST_FILEXT - The URL file extension.
  • REQUEST_TEMPLATESPATH - The Wordpress templates absolute file path.
  • REQUEST_TEMPLATESURL - The Wordpress templates relative URL path.
  • REQUEST_SITEID - The Wordpress multi-site id.
  • REQUEST_BLOGID - The Wordpress multi-site blog id.
  • REQUEST_PAGEID - The Wordpress page id. 
  • REQUEST_ISFRONTPAGE - A boolean value of whether the page is the homepage.  

Token Parameters

Optionally, tokens can pass parameters from page to token value for dynamic processing. The format to pass a parameter is fairly simple. {tokenname,"param1",param2}. The token supports string and integer parameters. The parameter can be accessed in the token value through PHP by $GLOBALS["ARGS"][0]. Change the index id to access the other specified parameters.

Accessing Wordpress API

In this section, I will show you how to access the Wordpress API from your PHP token value, to make something worth wild. Lets start by creating a new token.

Token Name: randomlatestposts
Token Type: control
Token Description: Grabs latest post ids and adds them to an array, then shuffles the ids and pulls in a random specified amount. Two parameters, listsize and returnlimit.

Token Value: HTML Tab
HTML
<?php echo $randomlatestposts->get($GLOBALS["ARGS"][0], $GLOBALS["ARGS"][1]); ?> 
Token Value: PHP Tab
PHP
class randomlatestposts
{
 public function get($_listsize, $_returnlimit)
 {
   global $wpdb;
   
   $posts = "SELECT id from $wpdb->posts " .
            "WHERE post_type='post' AND post_status='publish' " .
            "ORDER BY post_date DESC LIMIT $_listsize";
   $postarray = array();
   $postresult = mysql_query($posts) or die(mysql_error());

   while ($row = mysql_fetch_array($postresult)) { $postarray[] = $row[0]; }

   shuffle($postarray);
   array_splice($postarray, $_returnlimit);

   $ids = implode(',', $postarray);

   $args = array(
	'showposts'=> $_returnlimit,
	'post__in' => explode(',', $ids),
	'orderby' => 'rand');
   
   query_posts($args);

   $html = '';
   while (have_posts())
   {
     the_post(); 
     $html .= '<li style="margin-bottom: 5px;">' .
              '<a href="' . get_permalink() . '" rel="bookmark">' . 
              get_the_title() . '</a></li>';
   }
   
   return '<ol>' . $html . '</ol>';
 }
}

$randomlatestposts = new randomlatestposts(); 

Add in token code '{randomlatestposts, 300, 5}' in your theme or page and assign it. The code will pull from 300 of the latest posts back, randomize the ids and pull back 5 for display on your page. In the PHP token value, you will notice i used 'global $wpdb'. This gives me access to the Wordpress database directly. I also included non direct Wordpress API function calls too. I gave you both examples in the same code to show you how diverse you can make your tokens.

Image 5 

Token History, Versioning, Backup and Restore

I have integrated a scrum process for managing versions with the Tokens. It is only available in the professional version of the Token Manager. Although, the standard free version does contain pieces of the code to keep your code safe from overwrite. Each time you update a token, the full token will be moved into a separate table and the version will be increased. If you would like to access the token versions you will need to do it directly from the database in the standard version.

Conclusion 

I hope you enjoyed my latest article on 'How to use the Token Manager plugin for Wordpress'. Have fun, building more resilient, easier to understand Wordpress websites. Please post any questions or concerns below. I will try to answer them in a timely fashion.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) Codevendor
United States United States
Please visit my personal website https://codevendor.com for my latest codes and updates.

Comments and Discussions

 
SuggestionHow To Build a WordPress Website Offline Pin
Member 1352828518-Nov-17 3:27
Member 1352828518-Nov-17 3:27 
GeneralMessage Closed Pin
10-Jul-18 22:29
lucywilson10-Jul-18 22:29 
PraiseNice Pin
MarkWebber20-Aug-17 8:25
MarkWebber20-Aug-17 8:25 
GeneralMy vote of 5 Pin
Christian Amado28-Aug-12 12:52
professionalChristian Amado28-Aug-12 12:52 
GeneralMy vote of 5 Pin
JavaWebDev28-Aug-12 6:40
JavaWebDev28-Aug-12 6:40 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.