Category — howto
Anatomy of a wordpress plugin
This article is the first in a series of how-to articles which will go through all the steps required to create a wordpress plugin.
At the end of the article, there will be a download link to a working plugin that you can download and use as a template for building your own plugins. The latest version of Wordpress is required (2.8.5), which is the version I used when writing this article. Earlier versions might also work, but I can’t guarantee it.
The first step is to create a new php file called testplugin.php
/*
Plugin Name: Rawseo - test plugin template
Plugin URI: http://www.rawseo.com
Description: A great plugin template
Version: 1.0
Author: Rawseo
Author URI: http://www.rawseo.com
*/
?>
The comment headers in your main plugin file (everything above between (/* and */) give wordpress information about your plugin which is displayed on the plugin information screen.
If you were to upload our template plugin file right now to your Wordpress plugins directory (wp-content/plugins), you would see the following in your plugin manager:

Now, we are going to add a settings page for our new plugin.
/*
Plugin Name: Rawseo - test plugin template
Plugin URI: http://www.rawseo.com
Description: A great plugin template
Version: 1.0
Author: Rawseo
Author URI: http://www.rawseo.com
*/
function checkAuth()
{
return current_user_can('activate_plugins');
}
function settings_subpanel()
{
global $wpdb; //this gives us access to the wordpress database
if (isset($_POST['new_email_address']))
{
update_option("admin_email",$wpdb->escape($_POST['new_email_address']));
}
echo '<div class="wrap">';
echo '<h2>Rawseo test plugin</h2>';
echo '<form action="" method="post">
<p>This plugin allows you to edit and save the wordpress admin email address</p>
Admin Email Address: <input type="text" size="20" name="new_email_address" value="'.get_option("admin_email").'"><br/>
<input type="submit" value="Save" /></form>';
}
function settings_page()
{
if (checkAuth())
{
if (function_exists('add_options_page'))
{
//add_options_page(page_title, menu_title, capability, file, [function])
add_options_page('Rawseo options','Rawseo test plugin','administrator', basename(__FILE__),
'settings_subpanel');
}
}
}
add_action('admin_menu', 'settings_page');
?>
Understanding how to create your own plugin first requires an explaination of some built-in wordpress functions that are required to properly communicate with various sections of your administration panel and blog.
Even though it’s at the end of the file, add_action starts the process rolling for the settings page. Wordpress allows you to hook into different events with your own functions, which can execute and process code at various times. Since we are adding a new settings page onto the administrative menu, ‘admin_menu’ is passed as the first parameter (which is the event) and ’settings page’ is passed as the second (this is our function that will be called for that event).
{
return current_user_can('activate_plugins');
}
CheckAuth() checks to see if the user has the correct permission to view or edit our plugin settings through a function called current_user_can.
The following is a list of all of the possible permissions that you can check:
- install_themes
- update_themes
- switch_themes
- edit_themes
- install_plugins
- activate_plugins
- edit_plugins
- update_plugins
- delete_plugins
- create_users
- edit_users
- delete_users
- edit_files
- manage_options
- import
- unfiltered_upload
- edit_dashboard
- moderate_comments
- manage_categories
- manage_links
- unfiltered_html
- edit_published_posts
- edit_others_posts
- edit_pages
- edit_others_pages
- edit_published_pages
- publish_pages
- delete_pages
- delete_others_pages
- delete_published_pages
- delete_others_posts
- delete_private_posts
- edit_private_posts
- read_private_posts
- delete_private_pages
- edit_private_pages
- read_private_pages
- upload_files
- publish_posts
- delete_published_posts
- edit_posts
- delete_posts
- read
add_options_page adds our new options page to the settings menu.
add_options_page(page_title, menu_title, capability, file, [function])
page-title: Text that will go into the HTML page title for the page when the menu is active.
menu-title: The on-screen name text for the menu.
capability: The minimum role required to display and use this menu page.
examples: Editor,Author,Contributor,Editor,Administrator
file: If the function parameter is omitted, this should be the PHP file that handles the display of the menu page content.
function: function that displays the page content for the menu page

settings_subpanel() displays all of the HTML that will be contained in the new settings page. I also used a couple of built-in functions that may help you when you build your own plugins.
update_option(): Update an option in the wp_options table.
get_option(): Get an option from the wp_options table
$wpdb->escape(): Used to prevent injection attacks by encoding certain characters. You should be ussing this function (or some other type of escaping) on any data sent into a database.
Download
This example plugin will display an input form which will allow you to update the current wordpress admin email address. If you would like to download the plugin example from this article, it can be found here.
November 17, 2009 Comments Off
How to cache smarty templates
What is caching?
Caching is used to speed up a call to display() or fetch() by saving its output to a file. If a cached version of the call is available, that is displayed instead of regenerating the output. Caching can speed things up tremendously, especially templates with longer computation times. Since the output of display() or fetch() is cached, one cache file could conceivably be made up of several template files, config files, etc.
Since templates are dynamic, it is important to be careful what you are caching and for how long. For instance, if you are displaying the front page of your website that does not change its content very often, it might work well to cache this page for an hour or more. On the other hand, if you are displaying a page with a weather map containing new information by the minute, it would not make sense to cache this page.
Setting it up
The first thing to do is enable caching by setting $caching = 1 (or 2).
Example: setting up caching
$smarty->caching = true;
$smarty->display('index.tpl');
?>
With caching enabled, the function call to display(’index.tpl’) will render the template as usual, but also saves a copy of its output to a file (a cached copy) in the $cache_dir. Upon the next call to display(’index.tpl’), the cached copy will be used instead of rendering the template again.
Technical Note: The files in the $cache_dir are named similar to the template name. Although they end in the “.php” extention, they are not really executable php scripts. Do not edit these files!
Each cached page has a limited lifetime determined by $cache_lifetime. The default value is 3600 seconds, or 1 hour. After that time expires, the cache is regenerated. It is possible to give individual caches their own expiration time by setting $caching = 2. See $cache_lifetime for more details.
example: setting up cache lifetime
// set the cache_lifetime for index.tpl to 5 minutes
$smarty->cache_lifetime = 300;
$smarty->display('index.tpl');
// set the cache_lifetime for home.tpl to 1 hour
$smarty->cache_lifetime = 3600;
$smarty->display('home.tpl');
// NOTE: the following $cache_lifetime setting will not work when $caching = 2.
// The cache lifetime for home.tpl has already been set
// to 1 hour, and will no longer respect the value of $cache_lifetime.
// The home.tpl cache will still expire after 1 hour.
$smarty->cache_lifetime = 30; // 30 seconds
$smarty->display('home.tpl');
?>
Caching Tips
Smarty caching can improve performance tremendously, but it doesn’t always work the way that you think it should. In the following situation (which I have seen recently):
example: within (main.tpl) (this is a file named main.tpl)
{include file="menu1.tpl"}
{elseif some other action}
{include file="menu2.tpl"}
{/if}
If the main template file (main.tpl) is cached, the includes template files will not get called properly. My solution is to separate the main file into cached and non-cached parts:
(within the PHP file that calls your smarty templates)
$smarty->caching = true;
//the fetch command puts the output of a template file into a variable rather than //the screen
$menu1 = $smarty->fetch('menu1.tpl');
$smarty->assign('menu1',$menu1);
$menu2 = $smarty->fetch('menu2.tpl');
$smarty->assign('menu2',$menu2);
//set the main caching file to false
$smarty->caching = false;
$smarty->display('main.tpl');
(within the new main.tpl)
{$menu1}
{elseif some other action}
{$menu2}
{/if}
July 14, 2009 2 Comments
Using smarty templates
Why use smarty templates?
One of Smartys primary design goals is to facilitate the separation of application code from presentation. Typically, the application code contains the business logic of your application, written and maintained in PHP code. This code is maintained by programmers. The presentation is the way your content is presented to the end user, which is written and maintained in template files. The templates are maintained by template designers.
At its most basic function, the application code collects content, assigns it to the template engine and displays it. The content might be something like the headline, tagline, author and body of a newspaper article. The application code has no concern how this content will be presented in the template. The template designer is responsible for the presentation. They edit the template files, adding markup and bringing it to completion. This typically involves things like HTML tags, cascading style sheets and other tools provided by the template engine.
This paradigm serves several purposes:
1) Designers can’t break application code. They can mess with the templates all they want, but the code stays intact. The code will be tighter, more secure and easier to maintain.
2) Errors in the templates are confined to the Smartys error handling routines, making them as simple and intuitive as possible for the designer.
3) With presentation on its own layer, designers can modify or completely redesign it from scratch, all without intervention from the programmer.
4) Programmers aren’t messing with templates. They can go about maintaining the application code, changing the way content is acquired, making new business rules, etc. without disturbing the presentation layer.
5) Templates are a close representation of what the final output will be, which is an intuitive approach. Designers don’t care how the content got to the template. If you have extraneous data in the template such as an SQL statement, this opens the risk of breaking application code by accidental deletion or alteration by the designer.
6) You are not opening your server to the execution of arbitrary PHP code. Smarty has many security features built in so designers won’t breach security, whether intentional or accidental. They can only do what they are confined to in the templates.
Although application code is separated from presentation, this does not necessarily mean that logic is separated. The application code obviously has logic, but the templates may have logic based on the condition that it is for presentation only. For example, if the designer wants to alternate table row colors or upper-case some assigned content, they can. This is presentation logic, something the programmer should not be concerned with. How often have you had some presentation displayed in a single column and then you wanted it in two or three columns, so the application code needs adjusting to accomodate this? A better approach is to assign the content in one single array and let the template handle the presentation. This will simplify your application and keep your templates flexible. Smarty supplies the tools to handle this kind of situation.
Getting Started with smarty
The first step is to download the smarty template engine Here
1. copy the following to a new file named “smartywrapper.php”
require_once('Smarty.class.php');
// extend the Smarty class
class smartywrapper extends Smarty {
//this will only work with php 5.X
function function __construct() {
// create the Smarty object
$this->Smarty();
// make sure these folders exist and the permissions are set accordingly
$this->template_dir = '/www/example.com/webapp/template/';
$this->compile_dir = '/www/example.com/webapp/compile/';
$this->config_dir = '/www/example.com/webapp/config/';
$this->cache_dir = '/www/example.com/webapp/cache/';
}
}
2. copy the following to a file named “smartytest.php”
require_once('smartywrapper.php');
// create the Smarty_WebApp object
$smarty = new smartywrapper();
// assign a variable, first parameter is the var name, second is the value
$smarty->assign('test_var_1','this is a test');
//display the template file (all html can now be placed here instead of in your php files)
$smarty->display('my_template.tpl');
create a file called my_template.tpl and place it in the directory in $this->template_dir = ‘/www/example.com/webapp/template/’; from above:
This is a test page from smarty, my variable is: {$test_var_1}
launch smartytest.php from your browser and if it is successful, you should see the following
Output
This is a test page from smarty, my variable is: this is a test
Conclusion
Smarty templates can not only be used to increase the overall speed of your php scripts through caching (more about caching can be found Here), but make it easier to develop large-scale applications through the separation of HTML code and php script.
July 9, 2009 2 Comments
How to get listed in google products
What is google products?
Many people don’t know that google has a search engine designed for products called google products. This service can be used to get more traffic to products on your website.

The first step is to signup with google base. Next, You can start adding your products.
There are a few ways to doing this:
1) one at a time

This is the easiest way to add a product. Google provides a step-by-step interface for adding individual products. This works well if you only have a couple of products.
2) Data feed
This format makes it easier to update large amounts of products at one time. Your feed file can be in a variety of different formats: text, XML, or shopping.com/shopzilla feeds.
Here is an example feed (all of these fields are required):
<g:condition>refurbished</g:condition>
<g:description>test description</g:description>
<g:id>01</g:id>
<g:link>http://www.mysite.com/product1</g:link>
<g:price>10.00</g:price>
<g:title>my new product</g:title>
</feed>
More information about this can be found here.
After your feed is setup, you can schedule when you want google to retrieve it (daily,monthly, or weekly) by clicking “create” under the schedule column. You just need to specify a link to the xml file (on your webserver).

3) google base data api
This is an XML based api that allows you to add, update, edit, and remove product information from your feed. More information about this can be found here.
July 2, 2009 No Comments
Better ways to improve php application performance
Google recently released a document on how to improve PHP performance here. Most of the tips listed here will not help you improve performance by any significant amount. The following is a list of things that you can do that will improve the performance of your web apps significantly.
1) object code caching
Each time a request comes to your server for a php script, it has to go through the compiler and then execute the object code. If this is cached, the 1st step is skipped and you end up with a faster and more responsive script.
There are many object code caching packages available on the Internet:
A) Ioncube: http://www.ioncube.com/
B) Zend Encoder: http://www.zend.com/products/zend_safeguard
2) Template systems
Template systems provide a different type of caching. Content caching. Template systems work well in a situation where there is static data on one or many of your pages that doesn’t have to be reloaded. Caching systems also provide a separation of code and html, which will not only improve completion time of the overall project, but make it easier for future improvments. Most template systems for php are available for free:
A) Smarty Templates: http://smarty.php.net/
B) Pear Templates: http://pear.php.net/package/html_template_it/redirected
C) PHP savant: http://phpsavant.com/yawiki/
3) Distributed object caching systems
The most widely used system of this type is memcached (http://www.danga.com/memcached/).
This type of system makes your overall site faster by caching the majority of your database data into a large memory pool.
more on memcached:
“Danga Interactive developed memcached to enhance the speed of LiveJournal.com, a site which was already doing 20 million+ dynamic page views per day for 1 million users with a bunch of webservers and a bunch of database servers. memcached dropped the database load to almost nothing, yielding faster page load times for users, better resource utilization, and faster access to the databases on a memcache miss.”
4) PHP variables that can be set
variables_order = ‘GPC’
register_argc_argv = ‘Off’
register_globals = ‘Off’ (this is a good idea to keep off for security purposes as well)
always_populate_raw_post_data = ‘Off’
magic_quotes_gpc = ‘Off’
Disable Error Logging. This is a good idea to keep on when you are developing your scripts, but it has been known to decrease overall performance.
Use IP addresses, rather than host names to access your database. Although this is sometimes not possible, you will get a slight boost in lookup speed if the IP address is used to access your database rather than its hostname.
5) Output Compression
Almost all browsers these days support something called gzip compression. Gzip compression can decrease the overall size of your output by up to 80%, but with a tradeoff: cpu usage will go up by around 10%. The benefit of using this compression type is the fact that not only will your bandwidth be decreased, but your pages will load faster.
enabling it in php (add the following lines to php.ini):
zlib.output_compression = On
zlib.output_compression_level = (level) (where level is 1-9. Youy may want to try different values to see what is best for your system).
if you are using apache, you can also enable the mod_gzip module. It is highly configurable, with the ability to modify output based on MIME types, files, or browser settings.
6) Other things that may help
when using a database, only retrieve the data that you are actually going to use. This may sound like a no-brainer, but I have often times worked on projects where the original programmer used (select * from mytable) when they could have used (select fieldIneed from mytable).
index database tables whenever possible
Learn more about this Here
June 25, 2009 13 Comments