Posts Tagged ‘ plugins ’

Create simple WordPress plugins

Creating a Simple WordPress Plugin

You can use this as a code snippet for your projects. I am going to create a simple plugin that does nothing but display “Hello World”. I’ll leave the actual functionality of the plugin to you

Create a new php file in your plugin directory called my-hello-world.php, and type the following plugin code:

<?php
/*
Plugin Name: Hello World
Plugin URI: http://lonewolf-online.net/
Description: Sample Hello World Plugin
Author: Tim Trott
Version: 1
Author URI: http://lonewolf-online.net/
*/function sampleHelloWorld()
{
echo “<h2>Hello World</h2>”;
}
?>

The lines inside /* and */ are used by WordPress to find out about the plugin. We have one function called sampleHelloWorld which does exactly that.

Now, traditionally we would have had to open up the sidebar of the theme you are using, find the location of where you want the Hello World displayed, and hard code the function in. Upload to the server and test. If for some reason there is a problem with your plugin (or a third party plugin) then your site would almost certainly stop working. Changing the location from the left to the right sidebar means editing both files accordingly. This isn’t very good.

Widgets

Widgets take away the need for editing the sidebar files of a theme and allow for a drag and drop interface in the admin panel. Lets have a look at how we can wiget enable our plugin.

Open up the Hello World plugin file again and add these lines:

function widget_myHelloWorld() {
?>
<h2 class=”widgettitle”>My Widget Title</h2>
<?php sampleHelloWorld(); ?>
<?php
}function myHelloWorld_init()
{
register_sidebar_widget(__(‘Hello World’), ‘widget_myHelloWorld’);
}
add_action(“plugins_loaded”, “myHelloWorld_init”);

The first function here is what will be displayed on the sidebar when its set-up correctly. Notice that we are calling on our old function. This is upgrading the existing plugin to be widget enabled. You can if you like replace the function call with the function statements and combine the two functions.

The second function is called by WordPress when the plugin is activated. It calls a WordPress function that will register a new widget which will be called “Hello World” which will call our new widget function.

Add action just tells WordPress to call myHelloWorld_init when the plugin is loaded.

Enhancements for Theme Compatibility

While this widget will function fine, we can make some improvements to enable greater theme compatibility – not everyone uses the same themes as you test on.

WordPress will pass parameters to your widget, which contain information about the sidebar and the CSS classes. We should process these parameters and output the correct tags, or you risk breaking some themes.

The first thing we need to do is change our sampleHelloWorld function so that it will accept parameters, then to process these parameters into variables. This is done using the extract function.

function widget_myHelloWorld($args) {
extract($args);
?>
<h2 class=”widgettitle”>My Widget Title</h2>
<?php sampleHelloWorld(); ?>
<?php
}

These two lines will allow us to reference some variables and output correct html structure for the theme being used. The most important variables are before_widget, after_widget, before_title and after_title. Previously we have surrounded the widget title with a hard coded H2 tag with a css class widgettitle, but many themes do not support these tags. They may use a div, or a h1 or a span, so we need our widget to be flexible.

function widget_myHelloWorld($args) {
extract($args);
echo $before_widget;
echo $before_title;?>My Widget Title<?php echo $after_title;
sampleHelloWorld();
echo $after_widget;
}

These changes will allow our plugin to use the same tags as the theme author informs us we need to use, and will allow your widget to look the same as the other widgets in the sidebar.

To configure these options inside a theme, please see the section below on theme support.

Complete Plugin:

<?php
/*
Plugin Name: Hello World
Plugin URI: http://lonewolf-online.net/
Description: Sample Hello World Plugin
Author: Tim Trott
Version: 1
Author URI: http://lonewolf-online.net/
*/function sampleHelloWorld()
{
echo “<h2>Hello World</h2>”;
}function widget_myHelloWorld($args) {
extract($args);
echo $before_widget;
echo $before_title;?>My Widget Title<?php echo $after_title;
sampleHelloWorld();
echo $after_widget;
}

function myHelloWorld_init()
{
register_sidebar_widget(__(‘Hello World’), ‘widget_myHelloWorld’);
}
add_action(“plugins_loaded”, “myHelloWorld_init”);
?>

Testing your Plugin

If you check your plugins page now, you should now have a new plugin listed called Hello World which you can activate. On the Presentation tab, select widgets, and you should see your new widget available to be dragged onto a sidebar. Save your changes and admire your new work.

t is more than likely that your WordPress Widget will need to have some user configurable settings, so why not include a settings form within your widget?These settings pages (admin panels, configuration screen and so on…) are accessed from within the Presentation » Widgets screen from WordPress 2 and from Design » Widgets in WordPress 2.5. When you add a widget to a sidebar, you may notice a little icon on the right hand side of the widget. Clicking on this will open up the widget admin panel where your users can customize your widget to their needs.

Lets use the code from the Hello World widget of the last tutorial and change it around so that we have a settings page. We will see how to create the settings page, how to store/save and retrieve/load settings using the WordPress database and how to handle user inputs.

<?php
/*
Plugin Name: Hello World
Plugin URI: http://lonewolf-online.net/
Description: Sample Hello World Plugin
Author: Tim Trott
Version: 1
Author URI: http://lonewolf-online.net/
*/function sampleHelloWorld()
{
echo “<h2>Hello World</h2>”;
}

 

function widget_myHelloWorld($args) {
extract($args);
echo $before_widget;
echo $before_title;?>My Widget Title<?php echo $after_title;
sampleHelloWorld();
echo $after_widget;
}

function myHelloWorld_init()
{
register_sidebar_widget(__(‘Hello World’), ‘widget_myHelloWorld’);
}
add_action(“plugins_loaded”, “myHelloWorld_init”);
?>

The first thing we are going to create is the icon on the Widget sidebar screen, and get it to open up a blank screen which we will later fill with input controls.

We need to create a function that will be used to display and process the options. The convention is to use the plugin name appended with _control for the control panel page.

function myHelloWorld_control()
{
}

We will come back to this function a bit later on. For now, we will just get WordPress to use our blank form.

In the _init function where we register the sidebar widget, we need to add another function call that will tell WordPress that we have a control panel associated with our plugin.

function myHelloWorld_init()
{
register_sidebar_widget(__(‘Hello World’), ‘widget_myHelloWorld’);
register_widget_control(   ‘Hello World’, ‘myHelloWorld_control’, 300, 200 );
}

This extra function specifies the title of the page, the function that will be called (in this example it does nothing yet) and the widget control panel screen will be 300 pixels wide by 200 pixels tall. You can test this now, or continue and add some content.

WordPress Options

Before we get started on the admin panel, lets first have a look at how we can use the WordPress options database to store values. WordPress has a nice function that will do all the hard work for you called update_option. This function simply takes a key name and the data to store under that key, be it a string, integer or an array. You should try and use a unique, but meaningful, key name to avoid conflicts with other plugins or WordPress itself. I also use a prefix of “widget_” to identify that the settings are for a widget.

The WordPress options database is a table called by default wp_options, and maintains a list of key name and value pairs.

update_options(“widget_myHelloWorld”, “This is a test”);

This will update the key named widget_myHelloWorld in the WordPress database and set the value to “This is a test”. You can retrieve the information at a later date using the get_option function. This function only takes one parameter – the key name to retrieve.

$title = get_option(“widget_myHelloWorld”);
echo $title;

In this example we would expect to see “This is a test” on the screen.

Constructing our Admin Page

I am going to create the admin panel in four stages in this tutorial, you may wish to merge these all into one, or do them in a different order – its entirely up to you.

1. Create the Form Controls

To begin with you are going to need a form design. In this example we are going to simply use a text box and a label. I’ll leave the for design to you!

Each line on the form should be contained within a paragraph block to keep a nice uniform spacing between all elements. By default the items will be centred on the form, so if you need them to be left or right aligned, you will need to specify this in the p tag.

This is the code for my simple html form. You must use unique name and id attributes on the form. You will notice that there is no <form> element in the code. This is because a form element is provided by WordPress which encompass all the widgets that have been loaded.

function myHelloWorld_control()
{
?>
<p>
<label for=”myHelloWorld-WidgetTitle”>Widget Title: </label>
<input type=”text” id=”myHelloWorld-WidgetTitle” name=”myHelloWorld-WidgetTitle” value=”” />
</p>
<?php
}

If you test now you should have a label and text box centred on the widget control form. It is more than likely that you will need more than one form control, however I will let you work on that now you have a grasp of the basics.

2. Get Existing Data and Default Values

The next stage it to populate the form controls with either default values, or values obtained from the database with the get_options function.

Lets get the data from the database, perform a test on it to see if we have valid data, fill the data with default values if necessary then populate the form controls.

function myHelloWorld_control()
{
$options = get_option(“widget_myHelloWorld”);
if (!is_array( $options ))
{
$options = array(
‘title’ => ‘My Widget Title’
);
}?>
<p>
<label for=”myHelloWorld-WidgetTitle”>Widget Title: </label>
<input type=”text” id=”myHelloWorld-WidgetTitle” name=”myHelloWorld-WidgetTitle” value=”<?php echo $options[‘title’];?>” />
</p>
<?php
}

 

The first new line in this code will get the previously stored values from the database. We then test the output variable to see if it is null (no data was retrieved from the database) and if it is we create a new array with one element for the widget title. This method will guarantee that we have a valid value for the title (or an other setting) from the database or a default value. We can then use the title stored in the array to output into the text box value attribute.

3. Get User Input and Store the New Settings

We need some way of capturing the value a user may type in the box and storing it in the database to be re-used. For this we will need another form element that will identify our data when it is submitted. This new element is a hidden value which we will test against.

function myHelloWorld_control()
{
$options = get_option(“widget_myHelloWorld”);
if (!is_array( $options ))
{
$options = array(
‘title’ => ‘My Widget Title’
);
}if ($_POST[‘myHelloWorld-Submit’])
{
$options[‘title’] = htmlspecialchars($_POST[‘myHelloWorld-WidgetTitle’]);
update_option(“widget_myHelloWorld”, $options);
}

 

?>
<p>
<label for=”myHelloWorld-WidgetTitle”>Widget Title: </label>
<input type=”text” id=”myHelloWorld-WidgetTitle” name=”myHelloWorld-WidgetTitle” value=”<?php echo $options[‘title’];?>” />
<input type=”hidden” id=”myHelloWorld-Submit” name=”myHelloWorld-Submit” value=”1″ />
</p>
<?php
}

In this new code segment, we look at the PHP POST variable for an element called myHelloWorld-Submit (the same as the hidden field) and if we found it we extract the widget title from the post variable. It is important to ensure that the code we are about to insert into the database does not contain any malicious code, so we can use the htmlspecialchars function to help prevent SQL injections. We then make a call to update_option to save the new values to the database.

4. Using the Data

What is the point of doing all this and not using the data? None what so ever. Using the data within the widget is just as easy (in fact its the same) as using the data on the form.

In our code that outputs the widget title, you simply need to get the values for the database with get_option, make sure we have valid information and then output the value. We have already seen this in action on the widget control stage, so I will just go straight to the full code listing for this tutorial.

Complete Code

<?php
/*
Plugin Name: Hello World
Plugin URI: http://lonewolf-online.net/
Description: Sample Hello World Plugin
Author: Tim Trott
Version: 2
Author URI: http://lonewolf-online.net/
*/function sampleHelloWorld()
{
echo “<h2>Hello World</h2>”;
}

 

function widget_myHelloWorld($args) {
extract($args);

$options = get_option(“widget_myHelloWorld”);
if (!is_array( $options ))
{
$options = array(
‘title’ => ‘My Widget Title’
);
}

echo $before_widget;
echo $before_title;
echo $options[‘title’];
echo $after_title;

//Our Widget Content
sampleHelloWorld();
echo $after_widget;
}

function myHelloWorld_control()
{
$options = get_option(“widget_myHelloWorld”);<br/>
if (!is_array( $options ))
{
$options = array(
‘title’ => ‘My Widget Title’
);
}

if ($_POST[‘myHelloWorld-Submit’])
{
$options[‘title’] = htmlspecialchars($_POST[‘myHelloWorld-WidgetTitle’]);
update_option(“widget_myHelloWorld”, $options);
}

?>
<p>
<label for=”myHelloWorld-WidgetTitle”>Widget Title: </label>
<input type=”text” id=”myHelloWorld-WidgetTitle” name=”myHelloWorld-WidgetTitle” value=”<?php echo $options[‘title’];?>” />
<input type=”hidden” id=”myHelloWorld-Submit” name=”myHelloWorld-Submit” value=”1″ />
</p>
<?php
}

function myHelloWorld_init()
{
register_sidebar_widget(__(‘Hello World’), ‘widget_myHelloWorld’);
register_widget_control(   ‘Hello World’, ‘myHelloWorld_control’, 300, 200 );
}
add_action(“plugins_loaded”, “myHelloWorld_init”);
?>

Bookmark and Share
Advertisements

Plans for implementing rotating banner image in WordPress

Problem: Implement a rotating banner image on this blog which is hosted by WordPress.com. This means I cannot install any WordPress themes that automatically support bnner rotation (e.g. the Mandigo theme suggested by Will Taylor.

There is a known approach that relies upon you having some disk space on a server that will let you run a PHP script. I’d like to avoid using that approach.

Instead, my hope is to cobble something together using Flickr, Pipes and a bit of CSS. The following is an attempt to outline what steps are necessary to test this out.
Flickr constraints

First stop is to see if the conditions of use on Flickr will allow this. Yep, the Flickr Community Guidelines seems to indicate that you can use your content on other sites, just make sure that is a link back.

So, I should be able to show a flickr photo in the banner as long as there is a link back to the page on Flickr it comes from.
Modify CSS to get image from pipes

Next step is to see if I can modify the CSS of the theme I’m using to include a banner image, and then perhaps to include a banner image from a Pipes.
Use pipes to extract a single image from a gallery

Next step, would be to figure out how to write a pipe that will extract a single image from a Flickr gallery. Once that’s working figure out how to loop through the contents of the gallery so that rotation through the images is achieved.
Figure out the link back to the flickr photo page

If that’s all working I need to figure out how to provide a link back to the original flickr page. A banner image in a blog header usually returns back to the home page for the blog. Thinking perhaps some additional text with the name of the image could be included with a link back to the flickr photo page.

Structure of a WordPress Plugins

One of the more important aspects of developing a WordPress plugin is how you structure it. This post will go over some tips on how to structure your plugin to organize your plugin resources and avoid naming collisions. Each plugin author is different in the way they structure a plugin, so these tips are merely my own personal preference. I’ll first briefly describe how a WordPress plugin works and then go into a plugin’s structure.

How a WordPress Plugin Works:

After placing a WordPress plugin into the “wp-content/plugins/” folder, the plugin should automatically be available to install.

When a plugin is “Activated”, this tells WordPress to load your bit of code on “each” page (including admin pages). This is why if you have many plugins activated, your WordPress installation may be very slow due to the amount of code being included. Since WordPress loads your code automatically when the plugin is activated, you can take advantage of this by tapping into the WordPress Plugin Application Program Interface (API). You can also access the WordPress template tags or create your own.
I suggest reading into the WordPress loop if you plan on making changes to the post content or comments. The WordPress loop is the loop that displays your posts. Some template tags will not work outside of this loop, so it is imperative that you know exactly where your code is executing. You can control this by taking advantage of actions and filters, which will be explained in later posts.

Folder Structure:

All WordPress plugins will be installed in the wp-content/plugins directory. Some plugin authors simply include a PHP file for their plugin, but I recommend always creating a folder to store your plugin.

I typically structure my plugin in this folder structure:

Plugin Folder Name (The name of your plugin with no spaces or special characters)

-> Main plugin php file
-> js folder (for JavaScript files)
-> css folder (for StyleSheet files)
-> php folder (for other PHP includes)

For example purposes, here is a sample structure I have created:

devlounge-plugin-series
-> devlounge-plugin-series.php
-> js
-> css
-> php

Within the devlounge-plugin-series folder, I would include just the main PHP file and put all other files in their respective folders. This structure will assist other plugin authors who look at your code to be able to tell what the main plugin file is and where all the supporting files are located.
WordPress also recommends placing images in their own directory and including a read  me file for your plugin.

Main Plugin File:

When you start a new plugin file, the first seven lines are the lines that describe your plugin.
PHP:
1.  <?php
2.  /*
3.  Plugin Name: Your Plugin Name Here
4.  Plugin URI: Your Plugin URI
5.  Version: Current Plugin Version
6.  Author: Who Are You?
7.  Description: What does your plugin do?

Line 3 allows you to name your plugin. Line 4 allows you to point a user to the web location of your plugin. Line 5 allows you to specify the current version. Line 6 allows you to specify the author of the plugin. Line 7 allows you to describe your plugin.

Shown below is an example of the code filled out:
PHP:
1.  <?php
2.  /*
3.  Plugin Name: Devlounge Plugin Series
4.  Plugin URI: http://www.devlounge.net/
5.  Version: v1.00
6.  Author: <a href=”http://www.ronalfy.com/”>Ronald Huereca</a>
7.  Description: A sample plugin for a <a
href=”http://www.devlounge.net”>Devlounge</a&gt; series.

Set Up a Class Structure:

You don’t have to be incredibly familiar with PHP Classes to develop a WordPress plugin, but it sure helps. A class structure is necessary in order to avoid naming collisions with other WordPress plugins. If someone out there sets up the same function name as yours in a plugin, an error will result and WordPress will be rendered inoperable until that plugin is removed. To avoid naming collisions, it is imperative that all plugins incorporate a PHP class structure. Here is some bare-bones code that will allow you to set up a class structure.

PHP:
1. if (!class_exists(“DevloungePluginSeries”)) {
2.     class DevloungePluginSeries {
3.        function DevloungePluginSeries() { //constructor
4.
5.        }
6.
7.     }
8.
9. } //End Class DevloungePluginSeries

What the above code does is checks for the existence of a class named DevloungePluginSeries. If the class doesn’t exist, the class is created.
Initialize Your Class The next bit of code will initialize (instantiate) your class.
PHP:
1. if (class_exists(“DevloungePluginSeries”)) {
2.     $dl_pluginSeries = new DevloungePluginSeries();
3. }

All the above code checks for is if the class DevloungePluginSeries has been created. If it has, a variable called $dl_pluginSeries is created with an instance of the DevloungePluginSeries class.

Set Up Actions and Filters:

The next bit of code sets up a place holder for WordPress actions and filters (which I will go over in a later post).
PHP:
1. //Actions and Filters
2. if (isset($dl_pluginSeries)) {
3.     //Actions
4.

5.     //Filters
6. }
7.
8. ?>

The above code checks to make sure the $dl_pluginSeries variable is set. If it is (and that’s only if the class exists), then the appropriate actions and filters are set up.

Seven Reasons to Write a WordPress Plugin

While writing the “How to Write a Plugin” series, I thought it would be beneficial to list some reasons why WordPress users would want to write a WordPress plugin in the first place. Listed below are seven reasons why a WordPress user should consider writing a WordPress plugin.

=>You like a plugin’s idea, but don’t like the plugin’s implementation:

Whether discovering WordPress plugins on Weblog Tools Collection, the official WordPress plugins directory, or the WordPress Plugin Database, you will inevitably find a plugin that meets your needs — sort of. You like the idea of the plugin, but not really the approach the plugin author took with it. Why not run with the original idea and create your own separate version?

=>You want to modify existing plugin code:

Sometimes the plugin’s output needs to be tweaked a little bit or some functionality you would like is missing. You can try convincing the plugin author to add your feature, but plugin authors are usually quite busy or they may not like your suggestion. It takes a lot of effort by a plugin author to provide support and field feature and bug requests for a plugin that is free. Sometimes the plugin is no longer supported by anyone. In the event the plugin author is unable to your needs, it will be up to you to take the initiative and modify the existing plugin code. If you do a good enough job and make enough changes, you can re-release the plugin as long as the original plugin was released under a GPL compatible license. Usually one of the first things I do when I install or test a new plugin is to look at the code and see what I can modify, what I can’t modify, and what I can possibly add or take away.

=> You want to extend a plugin:

Sometimes a plugin is good as it is, but you would like to build upon it and release your own version. For example, you may think a plugin would work better using AJAX, or would like to add more hooks so that it is compatible with other plugins. You may want to add an admin panel so you don’t have to dig through the code to change the output. As stated earlier, if a plugin is released as GPL compatible, you are free to release your own version.

=>You want portable theme code:

For those of us who opted to build a custom theme from scratch rather than download one, you may find yourself re-using code snippets all over the place. Wouldn’t it be better just to write your own plugin that combined all the little code snippets so that you could use them as template tags? The beauty of template tags is that you can re-use them over and over for your theme and any future ones you build. And you only have one place to change the code rather than several.

=>You are a theme designer:

I would argue that if you are a template designer for WordPress, the next logical step is to be a plugin author. Writing plugins gives you a more intimate knowledge of how WordPress behaves and allows you to extend the functionality of your released themes.

=>You want to make money:

A good plugin author can usually get paid on the side for custom work. Some plugin authors take donations as well or charge extra for providing support or for consulting. If you are a custom theme designer, you can package your custom plugins in with the theme for an extra charge.

When launching the Reader Appreciation Project, one of the goals I had was to rapidly build incoming links. The best way I knew how was to write some WordPress plugins and promote them. One of my plugins (WP Ajax Edit Comments) turned out to be very popular and has currently generated more than 100 incoming links.


WordPress plugin audio player

Vodpod videos no longer available.

more about "WordPress plugin audio player", posted with vodpod