WordPress Plugin: Hungred Smart Quotes

Hungred Dot Com is a web development site. We have many code that was encoded automatically by WordPress for no good reason. Hence, it makes most of our code ugly and unreadable. This is very frustrating as i will have to go through each and every post in Hungred Dot Com to search for any problem on the post! Hence, i created this plugin that will replace WordPress smart quotes function with another function that can take in the tag of my WordPress syntax plugin. For those post that are currently suffering from code formatting, i have also implemented a decoding mechanism in this plugin to prevent special tag within the syntax plugin from being misunderstood as PHP start tag such as

<?php

will not be interpreted as code but plain text on the screen! I will display a screen shot of what it does at the end of this article.

Description

This is a small plugin that replace the smart quotes function in WordPress that format/encode the code in WordPress. Hence, most symbols will be formatted/encoded by WordPress texturize function.

Example,

'&' (ampersand) becomes '&amp'
'"' (double quote) becomes '&quot' 
''' (single quote) becomes ''' 
'< ' (less than) becomes '&lt'
'>' (greater than) becomes '&gt'

The plugin will help solve the above problem and produce the result below,

Example,

'&amp' (ampersand) becomes '&'
'&quot' (double quote) becomes '"' 
''' (single quote) becomes ''' 
'&lt' (less than) becomes '< '
'&gt' (greater than) becomes '>'

A control panel is also provided in this plugin to add in special tag for your code or disable smart quote in WordPress.
This problem is due to external code format plugin that required special tag such as


in syntaxhigher evolved.
Upon, activate, all existing article that was previously formatted will be decoded by this plugin while future article will be protected by the replaced texturize function for WordPress (so that the plugin tells WordPress texturize function to include your special tag from encode/format).

Hence, this plugin still provides you with the functionality of smart quote with the additional add on features to ease your life.

Screen shot of the plugin

Here are the control panel of Hungred Smart Quote. Simple and clear.

hungred-smart-quotes-setting

How to use this plugin

Do the following and you can ignore it for the rest of your life!

  1. Install it into your wordpress site
  2. Activate Hungred Smart Quotes
  3. On setting, go to the control panel of Hungred Smart Quotes and decide whether to allow wordpress smart quote and what are the tag you used for your code plugin. I used syntaxhighlighter evolved which required
    
    

    to prevent WordPress from formatting my code

  4. DONE!

That's it!

Plugin

You can search for this plugin on WordPress repository by typing 'hungred' as search criteria. If you want to manually install this, the link is here

Example

We are all visualize people. This is what the plugin can do if you just leave it alone and regardless if you enable or disabled WordPress smart quotes, the decoding mechanism will still run!

Before
hungred-smart-quote-before-one

After
hungred-smart-quote-after-one

Before
hungred-smart-quote-before-two

After
hungred-smart-quote-after-two

WordPress Plugin Development Tips And Tricks

I have been developing WordPress plugin for a while now and it seems like there are always some correct and better ways of writing a particular code in WordPress than mindlessly trying to substitute it with pure PHP. However, these WordPress codes can only be found through countless reading and analyzing of codes from other WordPress sources. In this article, i will present as many tips and tricks i have seen in WordPress that can be very useful for wordpress plugin development.

Find Plugin Directory and URL With WordPress

Previously, i used to hard code the directory by using PHP function. However, after realize there is a better alternative in WordPress, i changed the way i find the plugin directory and URL.

In PHP,

$url = get_bloginfo('url')."/wp-content/plugins/plugin-name/images/hello.jpg";
$directory = dirname(__FILE__)."/plugin-name/images/hello.jpg";

Note: Using dirname(__FILE__) might not always end up on the plugin folder.

In WordPress,

$url = WP_PLUGIN_URL."/plugin-name/images/hello.jpg";
$directory = WP_PLUGIN_DIR."/plugin-name/images/hello.jpg";

Import CSS or JavaScript in WordPress

We love to code these import statement out to the function that performed the action. It can be on the admin page, write post page, home page, etc. But the correct way is to use WordPress action hook and built-in method.

Import CSS/JavaScript to Admin page

function hpt_loadcss()
{
	wp_enqueue_style('hpt_ini', WP_PLUGIN_URL.'/hungred-post-thumbnail/css/hpt_ini.css');
}
function hpt_loadjs()
{
	wp_enqueue_script('jquery');
	wp_enqueue_script('hpt_ini', WP_PLUGIN_URL.'/hungred-post-thumbnail/js/hpt_ini.js');
}
add_action('admin_print_scripts', 'hpt_loadjs');
add_action('admin_print_styles', 'hpt_loadcss');

Import to theme page

function ham_add_style()
{
	$style = WP_PLUGIN_URL . '/hungred-ads-manager/css/ham_template.css';
	$location = WP_PLUGIN_DIR . '/hungred-ads-manager/css/ham_template.css';
	if ( file_exists($location) ) {
		wp_register_style('template', $style);
		wp_enqueue_style( 'template');
	}
}
add_action('wp_print_styles', 'ham_add_style');

Both ways utilize the wp_enqueue_style/wp_enqeue_script method and action hook to import stylesheet and JavaScript properly into WordPress.

Separate Plugin Admin Code

This is only necessary if you are building a large plugin for WordPress. It is efficient to separate the admin codes from others by placing it on an external file so that the admin codes will not be complied by PHP when non-admin user or visitors are accessing your website.

if (is_admin())
include(‘admin.php’);

Secure your WordPress Query

Security something important for all of us. WordPress has a function escape() in their global variable $wpdb. It is best to use this for all data query in your WordPress to better secure your SQL query with the database to prevent any form of security attack. below shows an example,

 $welcome_name = "Mr. WordPress";
  $welcome_text = "Congratulations, you just completed the installation!";

  $insert = "INSERT INTO " . $table_name .
            " (time, name, text) " .
            "VALUES ('" . time() . "','" . $wpdb->escape($welcome_name) . "','" . $wpdb->escape($welcome_text) . "')";

  $results = $wpdb->query( $insert );

You may want to visit the presentation slide that have some interesting WordPress function used for securitySecure Coding with WordPress – WordCamp SF 2008 Slides

Use WordPress For Table Prefix

Never hard code your table prefix in WordPress! WordPress provides a variable in its global variable $wpdb that allows you to easily retrieve your table prefix.

global $wpdb;
$table_name = $wpdb->prefix . "liveshoutbox";

Get Absolute Path In WordPress

In WordPress, you can get the absolute path through the constant ABSPATH which is defined in WordPress.

require_once( ABSPATH . '/wp-includes/classes.php' );
require_once( ABSPATH . '/wp-includes/functions.php' );
require_once( ABSPATH . '/wp-includes/plugin.php' );

Determine Whether a Table Exist In WordPress

Wonder how to determine whether a table exist in your WordPress? You can use the following method to detect whether a particular table exist.

global $wpdb;
$table_name = $wpdb->prefix . "mytable";
if($wpdb->get_var("show tables like '$table_name'") == $table_name) {
	echo 'table exist!';
}

Always Record Table Version

This is an important tips. Always remember to record the version of your plugin table, so you can use that information later if you need to update the table structure. This can help in upgrading your table structure of the plugin in the future.

add_option("hungred_db_version", "1.0");

Create Table Using WordPress Method

This is important for many WordPress developers out there. Although we can create a table using the following method,

	$table = $wpdb->prefix."ham_form";
    $structure = "CREATE TABLE  `".$table."` (
		ham_id DOUBLE NOT NULL DEFAULT 1,
		ham_textarea longtext NOT NULL,
		ham_display longtext NOT NULL,
		UNIQUE KEY id (ham_id)
    );";
    $wpdb->query($structure);

Great! A table is created! Now, tell me how are you going to change this structure in the future? A better alternative is to use the function dbDelta in WordPress.

	$table = $wpdb->prefix."ham_form";
    $structure = "CREATE TABLE  `".$table."` (
		ham_id DOUBLE NOT NULL DEFAULT 1,
		ham_textarea longtext NOT NULL,
		ham_display longtext NOT NULL,
		UNIQUE KEY id (ham_id)
    );";
	require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
	dbDelta($structure);

Directly from WordPress,

The dbDelta function examines the current table structure, compares it to the desired table structure, and either adds or modifies the table as necessary, so it can be very handy for updates (see wp-admin/upgrade-schema.php for more examples of how to use dbDelta). Note that the dbDelta function is rather picky, however. For instance:

* You have to put each field on its own line in your SQL statement.
* You have to have two spaces between the words PRIMARY KEY and the definition of your primary key.
* You must use the key word KEY rather than its synonym INDEX

Hence, any update on the structure of the table will result in a change on the user plugin as well.

Use Nonces During Form Submission

Nonces are used as a security related protection to prevent attacks and mistakes. You can use Nonces to enhance your WordPress form. here is an example,

<form ...>
<?php
if ( function_exists('wp_nonce_field') )
	wp_nonce_field('hungred-post-form'+$uniqueobj);
?>
</form>

We are just using the method wp_nonce_field in WordPress to create a nonce field on the above example. Next, we will need to validate whether the nonce is valid by using the following method after the user have submitted the form. This should be placed before any action began.

<?php check_admin_referer('hungred-post-form'+$uniqueobj); ?>

Pretty easy for enhancing form in your WordPress plugin. But this is not all you can do. There is also Link nonce protection where link is attached with a Nonces. You can read more about Nonces from the below link.

They have better explanation and example to understand Nonce.

Speed up your WordPress plugin development with Ubiquity Firefox add-on

ubiquity

Ubiquity is a Mozilla Firefox add-on, developed by Mozilla Labs. It allows you to search WordPress and PHP (PHP) documentation in an instant. Safe time on Google, more time on development 😀

Tutorial: How to change plugin table structure in WordPress

Some of us will have problem updating or changing your table structure in your WordPress plugin after it has been released to the public. Many people will come up with different ideas to change their existing plugin structure to a new one. Idea such as checking for that particular column existence either through pure SQL or mixture of SQL and PHP. However, the approach here may be a bit overkill. There is a much simpler way.

Mistakes Made By WordPress Developers

In most plugin tutorial on Google, we will see the normal declaration that everyone is familiar.

$table = $wpdb->prefix."hungred_post_thumbnail";
$structure = "CREATE TABLE  `".$table."` (
	hpt_post varchar(255) NOT NULL,
	hpt_name longtext NOT NULL,
	hpt_url longtext NOT NULL,
	hpt_loc longtext NOT NULL,
	UNIQUE KEY id (hpt_post)
);";
$wpdb->query($structure);

This is the usual code instruction during a plugin tutorial. However, the problem with this is that it makes maintenance of plugin difficult. Assuming you are trying to update the table structure with the above statement. You will find difficulty and resort to different means of getting your plugin table structure updated while keeping the same declaration in WordPress. This is not the right way to create a WordPress table!

Powerful way of creating plugin table in WordPress

We need something more powerful to take the job. In WordPress, there is a function dbDelta which will compare the structure between the existing table and the one in the WordPress database. It will automatic update the missing or extra field and alter the table for you. However, this method doesn't exist in WordPress default setup. You will have to import update.php to get this function. Furthermore, dbDelta will required a few criteria to be met before it is usable.

  • You have to put each field on its own line in your SQL statement.
  • You have to have two spaces between the words PRIMARY KEY and the definition of your primary key.
  • You must use the key word KEY rather than its synonym INDEX

Hence, you will have the following declaration.

$table = $wpdb->prefix."hungred_post_thumbnail";
$structure = "CREATE TABLE `".$table."` (
	hpt_post varchar(255) NOT NULL,
	hpt_name longtext NOT NULL,
	hpt_url longtext NOT NULL,
	hpt_loc longtext NOT NULL,
	UNIQUE KEY id (hpt_post)
);";
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
dbDelta($structure);

Just that simple. Once you utilized this, changing the structure of your WordPress plugin table will be an ease.

WordPress Plugin: Hungred Image Fit

This plugin is something i build a few months ago but just published out to the public and share with you. This plugin basically do nothing unless there is a need to. Therefore, maintain the current efficiency rate of the website. This plugin helps you guys with large image that are so big when placed on your post that it went over shot your existing layout design. This is not desirable. Hence, a simple plugin is made to solve this problem (again this is a plugin for lazy or precautions people). I implement this plugin on Hungred.com and 1sitedaily.com.

Description

This is a very small and lightweight plugin that automatically adjust your images on your post with a maximum width. This is to eliminate the problem where your images are too large and overlap other parts of your website layout.
Any image that are greater than the maximum width is being adjust according to its ratio aspect. Those images that are smaller than the maximum width is being ignored
On the other hand, resized images also have its tag enhanced to have 'title' and 'alt' attributes for better SEO.

A control panel for adjusting the maximum width size is provided.

For version 0.7 onwards, there is a few new features.

  1. User now can resize post images with specific tag
  2. User can remove resize capability of a particular post by placing "noresize" on the alt attribute of the img tag
  3. User can resize a particular post by placing "resize" on the alt attribute of the img tag for user to have absolute control over resizing of image.
  4. Resize method has changed to an optimum one where resizing will not delay your website due to the waiting time for image detail using PHP getimagesize function.

Screen shot of the plugin

Here are the control panel of Hungred Image fit. Simple and clear.

hungred-image-fit

How to use this plugin

This plugin is a straight forward type of plugin. Do the following and you can ignore it for the rest of your life!

  1. Install it into your wordpress site
  2. Activate Hungred Image Fit
  3. On setting, go to the control panel of Hungred Image Fit and set the maximum width
  4. DONE!

That's it!

On version 0.7, there are more control over the resizing plugin. Here are some information.

  1. You can now resize post that associate with a particular tag. This is done on the admin page.
  2. You can manually disable resizing on certain image by placing "noresize" on the img tag alt attribute
  3. You can manually enable resizing for a particular tag that is not associate with any allowed tag by placing "resize" on the img tag alt attribute.
  4. You can place the key "resize" or "noresize" by using wordpress uploader too.

Plugin

You can search for this plugin on WordPress repository by typing 'hungred' as search criteria. If you want to manually install this, the link is here

Example

I guess its really hard to tell what does this plugin do. Since i used this on 1sitedaily.com, i will show you their example.

hungred-image-fit-example

hungred-image-fit-example-2

Prevent WordPress Plugin Update From Deleting Important Folder In Your Plugin

Many would know that i have build a powerful thumbnail plugin in WordPress. The plugin work perfectly fine for WordPress 2.8 below but once i updated my WordPress to version 2.8, something bad happen. Every single time whenever i update my WordPress plugin, WordPress will delete the plugin folder with everything included and install the latest plugin version. This post a problem to my plugin since all the images are stored inside the plugin folder. I search online but i couldn't get any help anywhere until i investigate the new version 2.8 core codes.

New Hooks in WordPress 2.8

In WordPress 2.8, it has added a new functionality to delete the previous version of the plugin and then install the latest plugin version into the exact same location. Lucky, it also includes a few more filter hook that did the delete and install process. In class-wp-upgrade.php located at /admin/includes/class-wp-upgrade.php, lines 403-409 you will notice the following few codes,

		add_filter('upgrader_pre_install', array(&$this, 'deactivate_plugin_before_upgrade'), 10, 2);
		add_filter('upgrader_clear_destination', array(&$this, 'delete_old_plugin'), 10, 4);
		//'source_selection' => array(&$this, 'source_selection'), //theres a track ticket to move up the directory for zip's which are made a bit differently, useful for non-.org plugins.

		$this->run(array(
					'package' => $r->package,
					'destination' => WP_PLUGIN_DIR,
					'clear_destination' => true,
					'clear_working' => true,
					'hook_extra' => array(
								'plugin' => $plugin
					)
				));

		//Cleanup our hooks, incase something else does a upgrade on this connection.
		remove_filter('upgrader_pre_install', array(&$this, 'deactivate_plugin_before_upgrade'));
		remove_filter('upgrader_clear_destination', array(&$this, 'delete_old_plugin'));

I went to search on Google again for these new hook and it seems like there are a couple more of these new hooks being added into WordPress 2.8. But we are particularly interested on 'upgrader_pre_install' and 'upgrader_post_install' filter hook.

Using upgrade_pre_install filter hook

function hpt_copyr($source, $dest)
{
    // Check for symlinks
    if (is_link($source)) {
        return symlink(readlink($source), $dest);
    }

    // Simple copy for a file
    if (is_file($source)) {
        return copy($source, $dest);
    }

    // Make destination directory
    if (!is_dir($dest)) {
        mkdir($dest);
    }

    // Loop through the folder
    $dir = dir($source);
    while (false !== $entry = $dir->read()) {
        // Skip pointers
        if ($entry == '.' || $entry == '..') {
            continue;
        }

        // Deep copy directories
        hpt_copyr("$source/$entry", "$dest/$entry");
    }

    // Clean up
    $dir->close();
    return true;
}
function hpt_backup()
{
	$to = dirname(__FILE__)."/../hpt_images_backup/";
	$from = dirname(__FILE__)."/images/";
	hpt_copyr($from, $to);
}
function hpt_recover()
{
	$from = dirname(__FILE__)."/../hpt_images_backup/";
	$to = dirname(__FILE__)."/images/";
	hpt_copyr($from, $to);
	if (is_dir($from)) {
		hpt_rmdirr($from);#http://putraworks.wordpress.com/2006/02/27/php-delete-a-file-or-a-folder-and-its-contents/
	}
}
add_filter('upgrader_pre_install', 'hpt_backup', 10, 2);
add_filter('upgrader_post_install', 'hpt_recover', 10, 2);

In order to prevent WordPress plugin update from deleting our important folder within our plugin, we must move that particular folder somewhere safe before it starts deleting everything in our plugin. After the update has completed, we will then move the folder that we want to preserved and overwrite any existing files in that folder. We can't remove the filter action as shown on the core WordPress code was because the filter was not added previously. Thus, removing the filter will not prevent the deletion.