Pages

Thursday, 29 May 2014

Building Custom Widgets WordPress

Building WordPress widgets is just like building a plugin but it is more simple and straightforward. All you need to do is have a single file in which all the PHP goes and it's easier to code than a plugin which can have more than one file. There are three major functions of a widget which can be broken down into widget, update and form.
  • function widget()
  • function update()
  • function form()

Basic Structure

The basic outline of our widget is very simple and there are a handful of functions that you'll need to know. The bare bone structure of our widget is something like this:










add_action( 'widgets_init', 'register_my_widget' ); // function to load my widget
function register_my_widget() {}                        // function to register my widget
class My_Widget extends WP_Widget () {}     // The example widget class
function My_Widget() {}                     // Widget Settings
function widget() {}                        // display the widget
function update() {}                        // update the widget
function form() {}                          // and of course the form for the widget options

Step 1

Before we do all that we'll first load our widget whenever necessary by the function "widget_init". This is an action hook and you can find more about it in the WordPress codex.

add_action( 'widgets_init', 'register_my_widget' );
Next thing that we'll do is register our widget in WordPress so that it is available under the widgets section.

function register_my_widget() {
    register_widget( 'My_Widget' );
}

Step 2

We will enclose our widget in a class. The name of the class is important! One thing that should be kept in mind is that the name of the class and the name of the function should be the same.
1
class My_Widget extends WP_Widget {}
Now we'll pass some setting parameters to this class. For example we can pass this the width and height. We can also give our widget a little description if we want to, which is useful if you are bundling this widget with your commercial theme.

function My_Widget() {    function My_Widget() {
        $widget_ops = array( 'classname' => 'example', 'description' => __('A widget that displays the authors name ', 'example') );
        $control_ops = array( 'width' => 300, 'height' => 350, 'id_base' => 'example-widget' );
        $this->WP_Widget( 'example-widget', __('Example Widget', 'example'), $widget_ops, $control_ops );
    }
Now that we have completed the basic requirements for our widget, we'll move our attention to the three functions that we talked about earlier which are the important functions or the main building blocks of our widget!

Step 3 Function Widget()

The first function is related with the display of our widget. We'll pass a couple of arguments to our widget function. We'll be passing arguments from the theme, which can be a title and other specific values. Next we are passing the instance variable, which is related with the class of our function.
1
function widget( $args, $instance )
After that we'll extract the values from the argument because we want the values to be available locally. If you don't know what this local variable is all about, just don't worry about it right now and simply add this step!
1
extract( $args );
Next up we will be setting the title and other values for our widget, which can be edited by the user under the widgets menu. We are also including the special variables like $before_widget, $after_widget. These values are handled by the theme.

$title = apply_filters('widget_title', $instance['title'] );
$name = $instance['name'];
$show_info = isset( $instance['show_info'] ) ? $instance['show_info'] : false;
echo $before_widget;
// Display the widget title
if ( $title )
    echo $before_title . $title . $after_title;
//Display the name
if ( $name )
    printf( '<p>' . __('Hey their Sailor! My name is %1$s.', 'example') . '</p>', $name );
if ( $show_info )
    printf( $name );
echo $after_widget;

Step 4 Update Function()

Next up is the update function. This function will take the user settings and save them. It will just update the settings according to the user's taste.

function update( $new_instance, $old_instance ) {
    $instance = $old_instance;
    //Strip tags from title and name to remove HTML
    $instance['title'] = strip_tags( $new_instance['title'] );
    $instance['name'] = strip_tags( $new_instance['name'] );
    $instance['show_info'] = $new_instance['show_info'];
    return $instance;
}
One thing to note here is that we are stripping the values so that any XHTML can be removed from the text which, in simple words, might affect the working of our widget.

Step 5 Form Function()

The next step will outline creating the form which will serve as the input box. This will take in the user defined settings and values. The form function can include checkboxes, text input boxes etc.
Before we create these input fields, we'll have to decide what to show when the user doesn't select anything from the widget. To do this we will pass some default values to it like title, description etc.
1
2
3
//Set up some default widget settings.
$defaults = array( 'title' => __('Example', 'example'), 'name' => __('Bilal Shaheen', 'example'), 'show_info' => true );
$instance = wp_parse_args( (array) $instance, $defaults ); ?>
Now we'll create the input text box. We will enclose these options within the paragraph enclosing tag.

// Widget Title: Text Input
<p>
    <label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e('Title:', 'example'); ?></label>
    <input id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" value="<?php echo $instance['title']; ?>" style="width:100%;" />
</p>
//Text Input
<p>
    <label for="<?php echo $this->get_field_id( 'name' ); ?>"><?php _e('Your Name:', 'example'); ?></label>
    <input id="<?php echo $this->get_field_id( 'name' ); ?>" name="<?php echo $this->get_field_name( 'name' ); ?>" value="<?php echo $instance['name']; ?>" style="width:100%;" />
</p>
// Checkbox
<p>
    <input class="checkbox" type="checkbox" <?php checked( $instance['show_info'], true ); ?> id="<?php echo $this->get_field_id( 'show_info' ); ?>" name="<?php echo $this->get_field_name( 'show_info' ); ?>" />
    <label for="<?php echo $this->get_field_id( 'show_info' ); ?>"><?php _e('Display info publicly?', 'example'); ?></label>
</p>

Conclusion

And that's it. You just made yourself a very nice and simple widget which displays the name of the author of the blog. Furthermore it gives the option to the user whether or not to show it publicly to the audience. Save the code in a PHP file and upload it to your theme directory. Call it in your functions.php. After that go to your widgets panel and you will see the newly created widget.
All the code is included in the download file so that makes it easier to copy and paste. Have fun!

Friday, 23 May 2014

Create a WordPress blog on Windows Server 2008 R2, IIS 7.5 and MySQL

I think it is fitting that my first ever post on this WordPress Blog would be about setting up a WIMP server (Windows Server 2008 R2, IIS, MySQL & PHP).
Being a former Windows Systems Administrator I wanted to keep as many components running on familiar Microsoft applications (IIS 7.5 & SQL Server 2008 R2) and found this article explaining how to do it. However, at the time of writing this article I found that the WordPress on SQL Server (wp-sqlsrv) distribution was unavailable* so the only option was to use MySQL. In retrospect I am very happy with this outcome as the process of learning about MySQL has been very enjoyable and so far has proven to be a very stable and easy-to-use database application .
* Please note that the WordPress on SQL Server (wp-sqlsrv) distribution is now available.

The Environment

  • Server: Rackspace Cloud VM running Windows Server 2008 R2
  • Web server: IIS 7.5
  • Database application: MySQL
This blog you are reading is running off the environment above. So far I have found it to be an excellent blogging platform.

Install IIS 7.5

Logically, the first step is to install the web server application, IIS 7.5. From this point onwards I will simply refer to it as IIS.  To do so, perform the folowing steps:
1. Click Start > Run then enter servermanager.msc in the Open dialogue box then click OK  to load Server Manager:
C:\>servermanager.msc
2. Once Server Manager has loaded, right-click on Roles and click Add Roles, which initiates the Add Roles Wizard:
3. Click Next in the Before You Begin section:

4. Select Web Server (IIS) on the Select Server Role section and click Next:
20120416220536
5. Select the IIS services to be installed on the Select Role Services page. Keep the defaults but also select the CGI check box under Application Development. This enables both the CGI and FastCGI services which is required to use PHP:

6. Click Next and on the Confirmation page click Install.
7. Once the installation has completed, click Start > Run and then enter inetmgr in the dialogue box then click OK to load Internet Information Services (IIS) Manager. This will fire up IIS Manager and you will see IIS running and configured according to the options you selected earlier:

For more information, this article shows how to install IIS 7.5 with default settings and this article shows how add the CGI feature as described above.

Configure IIS 7.5

We now need to configure IIS in preparation for WordPress:
8. Click Start > Run and enter CMD in the dialogue box and then click OK.
9. At the command prompt enter the following and then hit enter on the keyboard:
md C:\Websites\Wordpress
This creates the directory where the new WordPress site will be located.
10. Open IIS Manager and click on Sites.
11. Right-click on Sites and then click Add Web Site:

In the Add Web Site dialogue box enter these details:
  • Name: WordPress
  • Physical path: C:\Websites\Wordpress
  • Bindings: All Unassigned. If your server has multiple IP addresses and you want the site to listen on a specific IP address select it from the drop-down box.
  • Host name: www.yourdomain.name. This should contain the fully-qualified domain name for your blog site.

Once all the sections have been completed click OK. You will now see the WordPress site under the Sites folder.
12. Click on Application Pools and in the middle pane you will see an application pool named WordPress. Right-click on it and select Advanced Settings:

13. Find the setting Enable 32-Bit Applications and click the drop-down box and click True. Click OK to save the settings:
20120417065550
We will leverage the improved security in IIS 7.5 by utilising ApplicationPoolIdentity. More information about this can be found here.
14. Select the WordPress site in the Connections pane and then double-click Authentication:

15. Select Anonymous Authentication and in the Actions pane on the right side click Edit:

16. Then select Application Pool Identity and click OK:

17. Click Start > Run and then enter CMD in the Open dialogue box then click OK  to load a command prompt enter the following and hit enter:
icacls "C:\Websites\Wordpress" /grant "IIS APPPOOL\Wordpress":(OI)(CI)(RX,W)
This configures the WordPress application pool to have write permissions to the directory where the new WordPress site is located.

IIS is now configured and ready for PHP to be installed!

Install PHP 5.3.10 for Windows

WordPress uses PHP therefore it is the next component to be installed. We require a ‘Non Thread Safe’ version and facilitate the installation we will use the latest version that comes with an ‘Installer’. At the time of writing, version 5.3.10, has an Installer. To proceed, perform the following:
18. Go to http://windows.php.net/download/.  Find version 5.3.10, under VC9 x86 Non Thread Safe, click the Installer version to download it. Click here for a direct download.
19. Once downloaded, run the .msi setup file, click Next at the first screen and accept the EULA (End User License Agreement)  and then click Next again.
20. Keep the default installation directory, which is C:\Program Files (x86)\PHP:

21. At the Web Server Setup step select IIS FastCGI:

22. Install the following features also; Script Executable, Register *.php files to open automatically and PEAR Install:

23. Click Next then Install and then click on Finish to complete the setup:

Install PHP Manager 1.2
PHP Manager is a plugin for IIS that allows you to manage and configure PHP settings and installations.
24. Go to http://phpmanager.codeplex.com/ and click on ‘View all downloads’ and download and install the x64 version.
25. Open IIS Manager and in the Connections pane select the server name. In the middle pane you will see all installed features within IIS. Select and open PHP Manager:

26. Under the PHP Setup section select View Recommendations:

27. Select all of the recommendations and hit the OK button:

Install MySQL

At the time of writing, MySQL 5.5.21, is the most recent version available.
28. Go to http://dev.mysql.com/downloads/mysql/ and download the 64-bit MSI Installer and run the setup (mysql-5.5.21-winx64.msi)
29. Accept the EULA and click Next.
30. In the Choose Setup Type section select Typical and click Next:

31. In the Ready To Install MySQL 5.5 section click Install:

32. When the installation completes ensure Launch the MySQL Instance Configuration Wizard is ticked and then click Finish:

33. Select Standard Configuration as the configuration type and then Next:

34. Select Server Machine as the server type and then click Next:

35. In the Windows Options section ensure the settings match the image below:

36. In the security options section check Modify Security Settings, enter the root password of your choice and then click Next:

37. In the configuration section shown below click Execute:

38. Once the process completes click Finish:

Configure MySQL for WordPress

We will now create the database for WordPress within MySQL. We will do this via the command line client.
39. Click Start > All Programs > MySQL > MySQL Server 5.5 > MySQL 5.5 Command Line Client to open a MySQL command prompt:
40. Enter the root password you chose earlier in the MySQL setup and hit enter:

41. To create the WordPressDB database type the following and hit enter:
CREATE DATABASE WordPressDB;
You will receive a confirmation that the command was successful:
Query OK, 1 row affected (0.00 sec)
41. To create the wp_user and grant it access and requisite permissions to the WordPressDB database type the following and hit enter:
GRANT ALL PRIVILEGES ON WordPressDB.* TO "wp_user"@"localhost" IDENTIFIED BY "password";

Please note that the “;” signals the end of the command. To go to a second line just hit Enter without a “;” at the end of a line.
42. Type Exit and hit enter to exit the MySQL command line client.
The confirugration of MySQL is now complete. We should now have the following information available for the WordPress install:
  • Database Name: WordPressDB
  • Database User: wp_user
  • DB User Password: password

Install WordPress

Go to http://wordpress.org/download/ and download the latest version of WordPress (currently 3.3.1) and then folllow these steps:
43. Extract the WordPress files to the location of the WordPress site we created earlier in IIS - C:\Websites\Wordpress.
44. Navigate to C:\Websites\Wordpress and find the file named wp-config-sample.php and open it with Notepad, as per below:

45. Ammend the following fields in wp-config-sample.php with the MySQL database info we created earlier :
  • DB_NAME: WordPressDB
  • DB_USER: wp_user
  • DB_PASSWORD: password
The screen shot below shows the variables that need to be changed. This is telling WordPress which database (WordPressDB) to store the configuration data in MySQL and also the connection information (wp_user and password) to be used:

46. Save the file as wp-config.php
47. Type in the following into your browser to start the WordPress installation script:
http://www.yourdomain.com/wp-admin/install.php
Be sure to replace www.yourdomain.com with your domain.
48. You will now see the WordPress welcome screen:

You need to configure the following fields with your own personal information:
  • Site Title: My First WordPress Blog
  • Username: choose your username (default is admin)
  • Password: choose your password
  • Your E-mail: email@yourdomain.com
49. Click the Install WordPress button and the setup script will run and you should see the following page soon after:
20120417114254
50. Click Login to go to the Admin Login page then enter your WordPress username and password you created earlier and start blogging!
I think it is fitting that my first ever post on this WordPress Blog would be about setting up a WIMP server (Windows Server 2008 R2, IIS, MySQL & PHP).
Being a former Windows Systems Administrator I wanted to keep as many components running on familiar Microsoft applications (IIS 7.5 & SQL Server 2008 R2) and found this article explaining how to do it. However, at the time of writing this article I found that the WordPress on SQL Server (wp-sqlsrv) distribution was unavailable* so the only option was to use MySQL. In retrospect I am very happy with this outcome as the process of learning about MySQL has been very enjoyable and so far has proven to be a very stable and easy-to-use database application .
* Please note that the WordPress on SQL Server (wp-sqlsrv) distribution is now available.

The Environment

  • Server: Rackspace Cloud VM running Windows Server 2008 R2
  • Web server: IIS 7.5
  • Database application: MySQL
This blog you are reading is running off the environment above. So far I have found it to be an excellent blogging platform.

Install IIS 7.5

Logically, the first step is to install the web server application, IIS 7.5. From this point onwards I will simply refer to it as IIS.  To do so, perform the folowing steps:
1. Click Start > Run then enter servermanager.msc in the Open dialogue box then click OK  to load Server Manager:
C:\>servermanager.msc
2. Once Server Manager has loaded, right-click on Roles and click Add Roles, which initiates the Add Roles Wizard:
3. Click Next in the Before You Begin section:

4. Select Web Server (IIS) on the Select Server Role section and click Next:
20120416220536
5. Select the IIS services to be installed on the Select Role Services page. Keep the defaults but also select the CGI check box under Application Development. This enables both the CGI and FastCGI services which is required to use PHP:

6. Click Next and on the Confirmation page click Install.
7. Once the installation has completed, click Start > Run and then enter inetmgr in the dialogue box then click OK to load Internet Information Services (IIS) Manager. This will fire up IIS Manager and you will see IIS running and configured according to the options you selected earlier:

For more information, this article shows how to install IIS 7.5 with default settings and this article shows how add the CGI feature as described above.

Configure IIS 7.5

We now need to configure IIS in preparation for WordPress:
8. Click Start > Run and enter CMD in the dialogue box and then click OK.
9. At the command prompt enter the following and then hit enter on the keyboard:
md C:\Websites\Wordpress
This creates the directory where the new WordPress site will be located.
10. Open IIS Manager and click on Sites.
11. Right-click on Sites and then click Add Web Site:

In the Add Web Site dialogue box enter these details:
  • Name: WordPress
  • Physical path: C:\Websites\Wordpress
  • Bindings: All Unassigned. If your server has multiple IP addresses and you want the site to listen on a specific IP address select it from the drop-down box.
  • Host name: www.yourdomain.name. This should contain the fully-qualified domain name for your blog site.

Once all the sections have been completed click OK. You will now see the WordPress site under the Sites folder.
12. Click on Application Pools and in the middle pane you will see an application pool named WordPress. Right-click on it and select Advanced Settings:

13. Find the setting Enable 32-Bit Applications and click the drop-down box and click True. Click OK to save the settings:
20120417065550
We will leverage the improved security in IIS 7.5 by utilising ApplicationPoolIdentity. More information about this can be found here.
14. Select the WordPress site in the Connections pane and then double-click Authentication:

15. Select Anonymous Authentication and in the Actions pane on the right side click Edit:

16. Then select Application Pool Identity and click OK:

17. Click Start > Run and then enter CMD in the Open dialogue box then click OK  to load a command prompt enter the following and hit enter:
icacls "C:\Websites\Wordpress" /grant "IIS APPPOOL\Wordpress":(OI)(CI)(RX,W)
This configures the WordPress application pool to have write permissions to the directory where the new WordPress site is located.

IIS is now configured and ready for PHP to be installed!

Install PHP 5.3.10 for Windows

WordPress uses PHP therefore it is the next component to be installed. We require a ‘Non Thread Safe’ version and facilitate the installation we will use the latest version that comes with an ‘Installer’. At the time of writing, version 5.3.10, has an Installer. To proceed, perform the following:
18. Go to http://windows.php.net/download/.  Find version 5.3.10, under VC9 x86 Non Thread Safe, click the Installer version to download it. Click here for a direct download.
19. Once downloaded, run the .msi setup file, click Next at the first screen and accept the EULA (End User License Agreement)  and then click Next again.
20. Keep the default installation directory, which is C:\Program Files (x86)\PHP:

21. At the Web Server Setup step select IIS FastCGI:

22. Install the following features also; Script Executable, Register *.php files to open automatically and PEAR Install:

23. Click Next then Install and then click on Finish to complete the setup:

Install PHP Manager 1.2
PHP Manager is a plugin for IIS that allows you to manage and configure PHP settings and installations.
24. Go to http://phpmanager.codeplex.com/ and click on ‘View all downloads’ and download and install the x64 version.
25. Open IIS Manager and in the Connections pane select the server name. In the middle pane you will see all installed features within IIS. Select and open PHP Manager:

26. Under the PHP Setup section select View Recommendations:

27. Select all of the recommendations and hit the OK button:

Install MySQL

At the time of writing, MySQL 5.5.21, is the most recent version available.
28. Go to http://dev.mysql.com/downloads/mysql/ and download the 64-bit MSI Installer and run the setup (mysql-5.5.21-winx64.msi)
29. Accept the EULA and click Next.
30. In the Choose Setup Type section select Typical and click Next:

31. In the Ready To Install MySQL 5.5 section click Install:

32. When the installation completes ensure Launch the MySQL Instance Configuration Wizard is ticked and then click Finish:

33. Select Standard Configuration as the configuration type and then Next:

34. Select Server Machine as the server type and then click Next:

35. In the Windows Options section ensure the settings match the image below:

36. In the security options section check Modify Security Settings, enter the root password of your choice and then click Next:

37. In the configuration section shown below click Execute:

38. Once the process completes click Finish:

Configure MySQL for WordPress

We will now create the database for WordPress within MySQL. We will do this via the command line client.
39. Click Start > All Programs > MySQL > MySQL Server 5.5 > MySQL 5.5 Command Line Client to open a MySQL command prompt:
40. Enter the root password you chose earlier in the MySQL setup and hit enter:

41. To create the WordPressDB database type the following and hit enter:
CREATE DATABASE WordPressDB;
You will receive a confirmation that the command was successful:
Query OK, 1 row affected (0.00 sec)
41. To create the wp_user and grant it access and requisite permissions to the WordPressDB database type the following and hit enter:
GRANT ALL PRIVILEGES ON WordPressDB.* TO "wp_user"@"localhost" IDENTIFIED BY "password";

Please note that the “;” signals the end of the command. To go to a second line just hit Enter without a “;” at the end of a line.
42. Type Exit and hit enter to exit the MySQL command line client.
The confirugration of MySQL is now complete. We should now have the following information available for the WordPress install:
  • Database Name: WordPressDB
  • Database User: wp_user
  • DB User Password: password

Install WordPress

Go to http://wordpress.org/download/ and download the latest version of WordPress (currently 3.3.1) and then folllow these steps:
43. Extract the WordPress files to the location of the WordPress site we created earlier in IIS - C:\Websites\Wordpress.
44. Navigate to C:\Websites\Wordpress and find the file named wp-config-sample.php and open it with Notepad, as per below:

45. Ammend the following fields in wp-config-sample.php with the MySQL database info we created earlier :
  • DB_NAME: WordPressDB
  • DB_USER: wp_user
  • DB_PASSWORD: password
The screen shot below shows the variables that need to be changed. This is telling WordPress which database (WordPressDB) to store the configuration data in MySQL and also the connection information (wp_user and password) to be used:

46. Save the file as wp-config.php
47. Type in the following into your browser to start the WordPress installation script:
http://www.yourdomain.com/wp-admin/install.php
Be sure to replace www.yourdomain.com with your domain.
48. You will now see the WordPress welcome screen:

You need to configure the following fields with your own personal information:
  • Site Title: My First WordPress Blog
  • Username: choose your username (default is admin)
  • Password: choose your password
  • Your E-mail: email@yourdomain.com
49. Click the Install WordPress button and the setup script will run and you should see the following page soon after:
20120417114254
50. Click Login to go to the Admin Login page then enter your WordPress username and password you created earlier and start blogging!