WordPress Plugin Development Cookbook

By Yannick Lefebvre
  • Instant online access to over 7,500+ books and videos
  • Constantly updated with 100+ new titles each month
  • Breadth and depth in over 1,000+ technologies
  1. Preparing a Local Development Environment

About this book

WordPress is a popular, powerful, and open Content Management System. Learning to extend its core capabilities allows you to unleash its full potential, whether you're an administrator who cannot find the right extension, or a developer with a great idea to enhance the platform for the community, or a website designer/developer working to fulfill a client's needs. "WordPress Plugin Development Cookbook" is the perfect companion for plugin developers, offering easy-to-follow instructions to accomplish tasks that range from basic plugin creation and configuration to advanced customization techniques. Each topic is illustrated through realistic examples showing how it can be applied to solve common problems, followed by explanations of all concepts used. Create WordPress plugins of varying complexity, from a few lines that change a specific function to complex extensions that provide intricate new capabilities. From the creation of your first simple plugin to adding entire new sections and widgets in the administration interface, learn how to change and extend WordPress to perform virtually any task. After installing and configuring an efficient plugin development environment, you will discover how to register your own callbacks that WordPress will execute at key points, forming the basis of plugin creation. Armed with this essential knowledge, you'll explore how to create administration pages to allow users to configure your new creations and to add new content management sections to WordPress through custom post types and custom database tables. Once you have all these elements in place, improve your plugins by customizing the post and page editors, creating user-facing forms to populate new content sections, making your plugin output dynamic using Javascript and AJAX as well as adding new widgets to the platform. Finally, see how to add support for multiple languages and distribute your work to the global WordPress community. "WordPress Plugin Development Cookbook" provides you with tools to create any plugin you can imagine.  

Publication date:
July 2012
Publisher
Packt
Pages
318
ISBN
9781849517683

 

Chapter 1. Preparing a Local Development Environment

We will cover the following topics in this chapter:

  • Installing a web server on your computer

  • Downloading and configuring a local WordPress installation

  • Creating a local Subversion repository

  • Importing initial files to a local Subversion repository

  • Checking out files from a Subversion repository

  • Committing changes to a Subversion repository

  • Reverting uncommitted file changes

  • Viewing file history and reverting content changes to older revisions

  • Installing a dedicated code/text editor

  • Installing and configuring the NetBeans Integrated Development Environment

  • Interacting with a Subversion repository from the NetBeans interface

  • Managing a MySQL database server from the NetBeans interface

Introduction

Before we start writing our first WordPress plugin, it is important to have a good set of tools in place that will allow you to work locally on your computer and be more efficient in your work. While it is possible to perform some development tasks with the built-in tools that are provided with the operating system, creating a solid local development environment will help you develop plugins quickly and have full control over your server settings to be able to test different configurations.

This chapter proposes a set of free tools that can easily be installed on your computer, regardless of your preferred operating system, to facilitate the development of your future WordPress plugins. These tools include a local web server to speed up page access and avoid sending files constantly to a remote server, a version control system to keep incremental backups of your work, a code editor for basic file editing capabilities, and an integrated development environment to accelerate your development tasks. In addition to installing and learning how to use these tools, this chapter also shows how to download and configure a local WordPress installation on a local web server.

 

Introduction


Before we start writing our first WordPress plugin, it is important to have a good set of tools in place that will allow you to work locally on your computer and be more efficient in your work. While it is possible to perform some development tasks with the built-in tools that are provided with the operating system, creating a solid local development environment will help you develop plugins quickly and have full control over your server settings to be able to test different configurations.

This chapter proposes a set of free tools that can easily be installed on your computer, regardless of your preferred operating system, to facilitate the development of your future WordPress plugins. These tools include a local web server to speed up page access and avoid sending files constantly to a remote server, a version control system to keep incremental backups of your work, a code editor for basic file editing capabilities, and an integrated development environment to accelerate your development tasks. In addition to installing and learning how to use these tools, this chapter also shows how to download and configure a local WordPress installation on a local web server.

 

Installing a web server on your computer


The first step to configure a local development environment is to install a local web server on your computer. This will transform your computer into a system capable of displaying web pages and performing all tasks related to rendering a WordPress website locally.

Having a local web server has many benefits:

  • Provides a quick response to the frequent page refreshes that are made as plugin code is written, tested, and refined, since all information is processed locally

  • Removes the need to constantly upload new plugin file versions to a remote web server to validate code changes

  • Allows development to take place when no Internet connection is available (for example, when traveling on an airplane)

  • Offers a worry-free programming environment where you cannot bring down a live website with a programming error or an infinite loop

There are many free packages available online that contain all of the web server components necessary to run a WordPress installation. This recipe shows you how to easily install one of these packages.

How to do it...

  1. 1. Visit the XAMPP website (http://www.apachefriends.org/en/xampp.html) and download the appropriate XAMPP package for your computer.

    Note

    XAMPP is available for the Windows, Mac OS X, and Linux platforms. The screenshots in this recipe were taken from XAMPP version 1.7.5 for Windows. The installation steps and exact dialog contents might vary slightly based on your choice of platform.

  2. 2. Optional on Windows: Disable the Windows User Access Control (UAC) feature to give full permissions to XAMPP to install itself on your system (visit http://windows.microsoft.com/en-US/windows7/Turn-User-Account-Control-on-or-off for more information on how to perform this procedure).

  3. 3. Launch the XAMPP installer (xampp-win32-1.7.5-VC9-installer.exe on the Windows platform).

  4. 4. Select your language of choice and acknowledge the warning message about User Access Control (UAC).

  5. 5. If possible, do not modify the default installation directory of c:\xampp since some references to this folder will be made in this book.

  6. 6. Uncheck the Create a XAMPP Desktop icon option, unless you want to have an icon for the web server on your desktop.

  7. 7. Check the Install Apache as service option to automatically start the web server when your computer starts.

  8. 8. Check the Install MySQL as service option to automatically start the database server when your computer starts.

  9. 9. Leave the Install Filezilla as service option unchecked since we will not need a local FTP server during the development of WordPress plugins.

  10. 10. Click on the Install button to proceed with the web server installation.

  11. 11. Click on Finish once the installation is complete. The XAMPP installer will register the necessary services with Windows based on the options selected during the installation process.

  12. 12. Launch the XAMPP Control Panel using the Start Menu shortcut to verify the status of the web and database servers. Both the Apache and MySql services should be displayed as Running in XAMPP Control Panel Application.

  13. 13. Open a web browser and navigate to the address http://localhost to display your local web server's welcome page.

  14. 14. Open the c:\xampp\apache\conf\httpd.conf file in a text editor (for example, Notepad).

  15. 15. Search for the DocumentRoot configuration option and change its value to a different location on disk to avoid keeping your project files under the original installation directory. For example, you could set it to a new directory designed to hold your local development installation of WordPress, such as DocumentRoot "C:/WPDev".

    Note

    Notice that forward slashes are used in this path. You should be careful if you copy and paste a path from a file explorer window.

  16. 16. Search for the Directory option and change it to the same path that was used for the DocumentRoot, that is<Directory "C:/WPDev">.

  17. 17. Save and close the httpd.conf file.

  18. 18. Create the directory specified as DocumentRoot, if it does not already exist on your computer.

  19. 19. Open the XAMPP Control Panel.

  20. 20. Stop and re-start the Apache service for the new configuration to take effect.

    Note

    Trying to access the local web server's welcome page will no longer work after having performed steps 14 through 20, since the new directory specified is currently empty.

How it works...

The XAMPP package contains all of the components necessary to run a web server capable of hosting a WordPress website on your computer. These components include:

  • Apache web server

  • PHP interpreter

  • MySQL database server

  • phpMyAdmin database management interface

The XAMPP package also includes an FTP server tool called FileZilla Server. We do not need to install this service since we can just locally access the web server files.

Once XAMPP is installed and started, the keyword localhost that we type in the web browser is recognized by the operating system as a request to communicate with the web server on the local computer and the Apache web server displays the welcome page from its documentation.

The XAMPP documentation is a set of flat HTML files located in the c:\xampp\htdocs directory on the Windows platform. This is the web server's default working directory.

The last few steps of the recipe instruct the Apache web server to look for the local website's content in a new directory. This is a safety precaution to be sure that site files are not deleted inadvertently if XAMPP is uninstalled. It can also help in managing multiple sites on a single computer.

There's more...

While XAMPP is a full-featured local web server package and is available on the three major operating systems, there are many others available online. Here is a list of some of the most popular ones:

Note

For a more complete list of web server packages, visit http://en.wikipedia.org/wiki/List_of_AMP_packages.

Creating a remote web development environment

If it's not possible for you to set up a local web server to develop WordPress plugins, or if you are planning to share the development tasks with one or more people, then an alternative to setting up a local web server is to create a remote development environment.

The easiest way to create such an environment, assuming that you already have a web hosting account set up, is to create a subdomain off your main domain. This will allow you to create a standalone test installation for WordPress that will still provide safety from affecting a live site but will not carry the other benefits of a local installation.

See also

  • Downloading and configuring a local WordPress installation recipe

 

Downloading and configuring a local WordPress installation


The next component of our local development environment is to install WordPress on your local web server to run a fully working website and have all of its files hosted locally.

WordPress has always prided itself with its easy five-minute installation process. Installing it on a local web server is even easier and quicker than it would be on a live remote server. This recipe covers the creation of a MySQL database to store all data related to our new WordPress installation and the actual setup process.

Getting ready

This recipe assumes that you have a local web server installed on your computer. This web server can be a fresh install performed using the previous recipe or can be from a previous installation. The steps in the following section are written with a focus on new web servers. If you have created a new account to access the MySQL database or changed the root user's password, some of the steps will change slightly. The location of the phpMyAdmin tool might also be different if you are using a different web server than XAMPP. You should refer to your web server's documentation to find out what that address is.

How to do it...

  1. 1. In the web browser, navigate to the address http://localhost/phpmyadmin/ to access your web server's database administration tool.

  2. 2. Click on the Databases tab in phpMyAdmin.

  3. 3. Type the name of the new database to be created in the empty field below the words Create new database. In this case, we will use the name wordpressdev.

  4. 4. Click on the Create button to complete the database creation process.

  5. 5. Download the latest WordPress installation package from the official wordpress.org site. The download link can be found on the very first page of the site and the download package will work on any web server, local or remote.

    Note

    The following instructions have been tested against WordPress version 3.4. While the installation process does not usually change much between versions, there may be slight differences in these steps on newer versions.

  6. 6. Extract the WordPress archive file contents using your favorite file archiver utility or your operating system's built-in capabilities.

  7. 7. Copy the contents of the resulting wordpress folder to your local web server's web content directory (c:\WPDev, if you followed the previous recipe). You should not copy the wordpress folder itself unless you want the address of your WordPress website to be http://localhost/wordpress.

  8. 8. Direct your web browser to http://localhost to start the WordPress installation process. Click on the Create a Configuration File button to start the process. Click on the Let's Go button to start the configuration process.

  9. 9. Update the Database Name field to reflect the name of our newly-created database (wordpressdev).

  10. 10. Set the MySQL User Name to root.

  11. 11. Delete all characters from the MySQL Password to leave it empty, since local MySQL server root accounts are typically configured without any password.

  12. 12. Leave the Database Host field with its default value (localhost).

  13. 13. Change the Table Prefix field from its default value to wpdev_.

  14. 14. Click on the Submit button to validate the information entered. If any parameters are not entered correctly, or if the WordPress installation process cannot correctly access your database server, it will display an error page and give you an opportunity to make corrections. Click on the Run the install button for WordPress to create the required table structure in the designated MySQL database.

  15. 15. Specify a Site Title (for example, Development Site).

  16. 16. Set a Password for the admin user.

  17. 17. Enter your E-mail address in the appropriate field (although no e-mail will actually be sent on most local development installations).

  18. 18. If you are configuring a live external development server, uncheck the Allow search engines to index this site option since we do not want this development site to appear anywhere. Click on Install WordPress to complete the installation. Click on the Log In button to navigate to your site's login screen.

  19. 19. Click on the Back to Development Site link to see your new site.

How it works...

In the first few steps, the phpMyAdmin interface is used to create a database on the local MySQL server. This web-based database management tool comes bundled with XAMPP and most other web servers. The http://localhost/phpmyadmin address will always take you to the database administration tool, even if you relocate your web server's document root directory as documented in the previous recipe.

Once a database is created and the WordPress files have been copied to the correct location, pointing your browser to the local web server gets it to search through the document root directory to find HTML files to send back to the browser or PHP files to execute. In the case of WordPress, the web server finds the index.php file and executes it using its PHP interpreter. As the WordPress code is executed, it checks if a configuration file is present and launches the installation process when it does not find it. The WordPress code does not see any difference between the local web server that we are running it on and a remote live web server that would be accessible anywhere online.

While we specified an e-mail address for the administrator during the installation, some local web servers are not configured to send out e-mail messages so we will never receive any e-mail communication in these cases. It is preferable to use a remote server when developing and testing e-mail functionality in a plugin.

Once this recipe has been completed, you will have a fully functional WordPress installation in place.

 

Creating a local Subversion repository


Version control is an important part of any code development project to keep track of a project's history, to have full and organized backups, and to be able to easily roll back changes to get back to a known working state. Version control is also the best and most efficient way to share code and other files when developing a project in a team environment. In addition to being a great version control system that is easy to use and configure, Subversion (often referred to as SVN) is also the technology that manages all submissions on the official WordPress plugin directory. Therefore, by setting up and using a local Subversion repository during your initial plugin development, you will immediately be ready to share your creations with the community.

How to do it...

  1. 1. Visit the TortoiseSVN site (http://tortoisesvn.net/downloads.html) and download the free Subversion client for your version of Windows (32- or 64-bit).

    Note

    While this recipe focuses on the creation of a local repository on the Windows platform, equivalent tools for other platforms are discussed after the recipe steps, in the There's more... section.

  2. 2. Launch the TortoiseSVN installation program and install it using all the default installation options.

  3. 3. Create a new folder on your hard drive that will host the local Subversion repository (for example, c:\WPSVN).

  4. 4. Right-click on the new folder and select the TortoiseSVN | Create Repository Here menu item. TortoiseSVN will create the required file structure in the target directory and display a message indicating that the repository has been created successfully.

  5. 5. Click on the Start Repobrowser button to launch the repository navigation tool.

  6. 6. Type file:///C:/WPSVN in the URL selection dialog box. At this time, TortoiseSVN displays the contents of the repository, which is currently empty.

How it works...

Subversion is a free open source version control system that is designed to keep file revisions organized and backed up over the course of a project's development, as well as provide access to older versions of all files at any time. If you have ever found yourself copying a directory on your computer and giving each copy sequentially numbered names or adding dates to their names, then you will recognize that version control is really just a more organized and efficient method of achieving the same goal of keeping backups of known working versions of code files, and being able to access any older version of a file.

While the default Subversion interface is a set of command-line utilities, TortoiseSVN and many other client applications provide graphical tools to create, access, and manage local and remote repositories.

In addition to familiarizing yourself with this system for later use on wordpress.org, using a local Subversion repository will ensure that you will always have older versions of your plugins easily accessible in case a code change that you perform breaks your work and you cannot figure out how to get back to a working state.

There's more...

While there are many Subversion clients available online to interact with a repository, not all of them include the necessary administration tools to easily create a repository as shown in this recipe. You should look for these administration capabilities when searching for a Subversion client for non-Windows platforms.

On Mac OS X, Versions (http://versionsapp.com/) and Cornerstone (http://www.zennaware.com/cornerstone/index.php) offer similar capabilities but are paid applications.

On Linux, the PagaVCS tool (http://code.google.com/p/pagavcs/) is a free clone of TortoiseSVN that includes both client and administration capabilities to create local repositories.

Manual repository creation

If your Subversion client does not offer the ability to create a local repository, then you can download the Subversion command-line tools from the official Subversion website (http://subversion.apache.org/packages.html) and create a repository manually following instructions found in the online Subversion reference manual (http://svnbook.red-bean.com/).

Other version control systems

While Subversion is easy to learn and is the system that is used by WordPress on its official plugin repository, other version control systems such as Git (http://git-scm.com/) and Mercurial (http://mercurial.selenic.com/) are gaining traction in the open source development community and could also be considered to manage your plugin code.

See also

  • Importing initial files to a local Subversion repository recipe

 

Importing initial files to a local Subversion repository


Once you have a local repository in place, this recipe describes the steps required to add files and start tracking their revisions over time. To have the flexibility to create multiple plugins as discussed throughout this cookbook without having to worry about adding each of them to the repository individually, we will add the entire WordPress plugin directory to your local repository.

Getting ready

You should have already installed a Subversion client on your computer and created a local repository as described in the Creating a local Subversion repository recipe. These steps will be slightly different based on the Subversion client that you have selected and your operating system.

How to do it...

  1. 1. Navigate to the wp-content\plugins directory of your local WordPress installation (for example, c:\WPDev\wp-content\plugins, if you followed the previous recipe) with the file explorer.

  2. 2. Right-click in the folder and select the TortoiseSVN | Import menu item.

  3. 3. Enter the file location of your local Subversion repository in the URL of repository field (for example, file:///c:/WPSVN), if it is not already specified.

  4. 4. Write a message in the Import message field that gives an overview of the files that are being imported in the repository.

  5. 5. Click on the OK button to complete the Import process.

Once the Import operation has started, TortoiseSVN sends all selected files to the repository, displaying each of their names in the process. At the end of the Import operation, it also displays the revision number that it assigned to this first set of files.

How it works...

Using the Import Subversion feature copies all selected files to the repository. In addition to storing the files themselves, Subversion identifies each file with a revision number and an import message. The revision number is generated by Subversion and incremented every time a group of files is added. It is especially useful when searching through a file's history.

The import message is specified by the user and is actually optional. That being said, it is important to set meaningful import messages when adding files to a repository as it will make it easier for you to identify what these files are, the state that they are in, and the reason they were added to the repository when performing future searches.

While these steps have led to a successful import, you may be wondering why nothing changed in the plugin directory. The reason is that the import process only makes copies of the selected files to the Subversion repository. An additional step, called the Checkout process, needs to take place to start keeping track of changes and file history.

See also

  • Checking out files from a Subversion repository recipe

 

Checking out files from a Subversion repository


After performing an initial import of files to a Subversion repository, the files need to be checked out to really start working in a version control environment. This recipe explains how to check out files from your local repository and what the resulting file structure changes will be.

Getting ready

You should have already installed a Subversion client, created a local repository, and imported files before following this recipe. These steps will be slightly different based on the Subversion client that you have selected and the operating system you are using.

How to do it...

  1. 1. Navigate to the WordPress plugin directory of your local installation in the file explorer if you are not already there.

  2. 2. Right-click in the whitespace of the directory window and select the SVN Checkout... menu item.

  3. 3. Enter the file location of your local Subversion repository in the URL of repository field (for example, file:///c:/WPSVN), if it is not already specified.

  4. 4. Set the Checkout directory to the plugin folder of your local WordPress installation (for example, C:\WPDev\wp-content\plugins).

    Note

    By default, the TortoiseSVN client adds the word WPSVN at the end of the path used when performing checkouts. Be sure to remove that last part of the path so that all files that are checked out go to the correct location.

  5. 5. Click on Yes on the dialog asking if files should be checked in a folder that is not empty. At this time, TortoiseSVN will retrieve all files that were added to the repository and copy them locally.

  6. 6. Once the operation is complete, look back at the file listing in the plugins directory to see that it has changed from its previous state.

How it works...

Performing a Checkout operation takes copies of all files from the repository and places them in the target directory. It also creates .svn directories at all levels of the file hierarchy. Looking at the default WordPress plugin directory, we can see that two .svn folders have been created. The first is directly in the plugins directory while the second is in the akismet subdirectory.

By default, most operating systems do not show folders that have a period at the beginning of their name since this usually identifies hidden files and directories. To display hidden folders on the Windows platform, carry out the following steps:

  1. 1. Press the Alt key in the file explorer to display the menu system.

  2. 2. Select the Tools | Folder options... menu item.

  3. 3. Select the View tab.

  4. 4. Set the Hidden files and folders radio button to Show hidden files, folders and drives.

The .svn directory contains information on the address of the repository that is associated with the files in the current folder. It also contains an original version of each file that was checked out. These original files are used for Subversion to determine when changes have been made to each file relative to their state when they were checked out or updated. While it might seem a bit redundant to have an original copy of all files in the .svn folders when our repository is locally hosted, this functionality allows Subversion to identify file changes when working on a remote repository, such as the official WordPress plugin server, even when your computer is not connected to the Internet.

There's more...

As you work with Subversion and TortoiseSVN, files that you create, modify, and delete will go through a number of different states. The following section explains what each of them represents.

Subversion file statuses

The green check mark indicator shown over each file icon, after performing this recipe, shows us that our files and directories have not been modified since they were last checked out or updated. These indicators will change over time as we start modifying existing files and creating new ones. The following is a list of the most common statuses that files will have as you work on a project, along with their associated TortoiseSVN icons:

  • Normal (green check mark): The file or directory is in a normal state and has not changed since it was last checked out or updated.

  • Modified (red exclamation mark): The file or directory has been modified since it was last checked out or updated.

  • Non-versioned (blue question mark): The file or directory is not under version control.

  • Added (blue plus sign): The file or directory is new and has been marked to be committed to the repository in the next commit operation.

  • Deleted (red x icon): The directory has been deleted and will be removed from the repository in the next commit operation.

  • Ignored (grey do not pass symbol): This file or directory will never be sent to the repository and Subversion should stop checking for changes. This state is useful to keep private files, such as personal documentation or to-do lists, in the same directory as the plugin but without uploading them to the repository and tracking their history over time.

  • Conflicted (yellow exclamation mark): This icon appears in situations of conflict, typically when more than one person works on the same repository and multiple users made changes to the same file. While the Subversion client will normally try to merge these changes to create a single file, a conflicted state indicates that the system was not able to merge these changes automatically. Conflicted files need to be manually merged or the user needs to indicate if the file has priority over the version that is currently stored in the repository.

See also

  • Committing changes to a Subversion repository recipe

 

Committing changes to a Subversion repository


During the course of a project, plugin files will typically be created, modified, or deleted. These changes should be transmitted regularly to the Subversion repository to have proper backups of all files in a project. A good practice is to commit changes at least once a day, with more frequent commit operations taking place when specific milestones are reached in the implementation of a plugin's features.

This recipe indicates how to manage file creation, modification, and deletion operations to keep everything organized and mirrored in the Subversion repository.

Getting ready

You should have already installed a Subversion client, created a local repository, and imported and checked out files before performing the steps in this recipe. These steps will be slightly different based on the Subversion client that you have selected and the operating system you are using.

How to do it...

  1. 1. Navigate to the WordPress plugin directory of your local installation in the file explorer if you are not already there.

  2. 2. Open the hello.php file in a text editor.

  3. 3. Edit the plugin name on line 7 to change it from Plugin Name: Hello Dolly to Plugin Name: Goodbye Dolly.

  4. 4. Save and close the file. You should now notice that the modified file is identified by a red exclamation mark icon in the file explorer, indicating that it has been modified.

  5. 5. Create a new folder in the plugins directory named chapter1. The new folder will be displayed, along with a blue question mark icon, indicating that it is not currently under version control.

  6. 6. Right-click on the new folder and select the TortoiseSVN | Add... menu item to bring up the Add dialog.

  7. 7. Click on the OK button to queue the file to be added to the repository when changes are next committed.

  8. 8. Navigate to the chapter1 directory and create a new text file named example.txt.

  9. 9. Navigate back to the plugins directory.

  10. 10. Right-click on the index.php file and select the TortoiseSVN | Delete menu item. The selected file is immediately deleted and disappears from the file explorer.

  11. 11. Right-click in an empty part of the plugins directory and select the SVN Commit... menu item. This last step will display the Commit dialog, with a top section to write a message detailing the changes that are being committed, and a bottom section containing a file listing. Notice that all files but one have check marks next to them since they have either been recognized as being changed by the Subversion client or have been added or deleted through the TortoiseSVN interface. The file that does not have a check mark next to it is the text file that was created but not tagged to be included in the next commit operation using the TortoiseSVN contextual menu.

  12. 12. Type a message in the appropriate field indicating the reason for the operation.

  13. 13. Right-click on the chapter1/example.txt file and select the Add menu item to add it to the operation.

  14. 14. Click on the OK button to send all changes to the Subversion repository.

How it works...

Using the local data stored in the .svn folders, the Subversion client is able to analyze the directory contents and identify all files that are new, have been modified, or are missing since the last checkout or update operation was performed, and then generate a list of these changes.

When the commit operation is performed, new files are added to the repository, modified files are uploaded and stored next to their previous versions, while deleted files are tagged as no longer being part of the current project version. While some of these behaviors might seem strange, it's by preserving previous versions of files and even keeping files that are no longer part of a project that Subversion is able to let us navigate through a project's entire history.

While it is preferable to use the TortoiseSVN menu to mark files and directories for addition and to delete items that are no longer needed, it is also possible to perform these operations when the commit is about to take place, as we saw in the recipe steps.

There's more...

Before files are committed to the repository, many programmers and developers want to see what changes were made to the modified files, especially in an environment that promotes peer reviews before committing code changes.

Viewing the differences in modified files

By right-clicking on any modified file in the Commit dialog and selecting the Diff menu item, the TortoiseSVN client will display its built-in file differencing tool, highlighting the parts that are different between the last version of the files in the repository and the current version of this file. This allows users to see what changed at a glance and be sure that no code was modified inadvertently.

Updating files to latest repository version

If you are the only person committing files to a repository, and you are working on a single computer, then you will never need to use the SVN Update menu item. This function is designed to compare your local files with the repository and check if new files or new revisions are available in the repository that are not present locally. It will then apply all necessary changes to the local versions of these files. Remember to use the SVN Update option in TortoiseSVN regularly if you are working in a team environment or are developing a project across multiple systems.

See also

  • Reverting uncommitted file changes recipe

 

Reverting uncommitted file changes


Until a file is committed to a repository, it is possible to revert all changes made to it since the last checkout, update, or committal of that file. This recipe shows us how to revert changes made to one or more files.

Getting ready

You should have already installed a Subversion client, created a local repository, and imported and checked out files before performing the steps in this recipe. These steps will be slightly different based on the Subversion client that you have selected and the operating system that you are using.

How to do it...

  1. 1. Navigate to the WordPress plugin directory of your local installation in the file explorer if you are not already there.

  2. 2. Open the hello.php file in a text editor.

  3. 3. Edit the plugin name on line 7 to change it back from Plugin Name: Goodbye Dolly to Plugin Name: Hello Dolly.

  4. 4. Save and close the file. When using the TortoiseSVN client, the file is marked as modified in the file explorer with a red exclamation mark icon.

  5. 5. To show the changes that occurred between the current version of the file and its original state, right-click on the file and select the TortoiseSVN | Diff menu item.

  6. 6. Close the Diff tool.

  7. 7. To revert the file back to its state from the last committal, right-click on the file and select the TortoiseSVN | Revert menu item. The Revert dialog will be displayed with the selected file listed and checked.

  8. 8. Click on OK on the Revert dialog to restore the file.

    Note

    To revert multiple files to their previous state, right-click on an empty area of the file explorer and select the TortoiseSVN | Revert menu item. This will display the same dialog with a list of all files that have changed since the last commit operation. Select the files which should be reverted and click on the OK button to perform the reversions.

How it works...

The revert operation uses the saved copies of files that are stored in the .svn directories located throughout the file structure. These local files allow the Subversion client to perform a file reversion operation without needing to contact the repository, which may be remote once you start working in a team environment or publishing plugins to the official WordPress repository. The reversion operation simply discards the modified files and copies back the last saved copy to the working directory.

There's more...

While Subversion clients such as TortoiseSVN and many others offer a fairly full set of functionality to simplify file comparisons and other file manipulations, some of them also allow support for your favorite tools.

Configuring TortoiseSVN to use an external diff viewer

While TortoiseSVN offers a diff viewer, its results are not always easy to analyze. Therefore, it can be really useful to substitute it with an external tool such as WinMerge (winmerge.org). To perform this substitution, carry out the following steps:

  1. 1. Right-click in an empty area of a file explorer or the desktop and select the TortoiseSVN | Settings menu item.

  2. 2. Navigate to the External Programs | Diff Viewer section.

  3. 3. Set the top radio button to External.

  4. 4. Use the browse button (...) to navigate to the location of your external diff viewer and select its main program executable (for example, C:\Program Files (x86)\WinMerge\WinMergeU.exe).

See also

  • Viewing file history and reverting content changes to older revisions recipe

 

Viewing file history and reverting content changes to older revisions


As multiple versions of files are committed to a repository over time, Subversion keeps track of all versions of these files along with the messages that were associated with each commit operation. On occasion, during a plugin's development, it may be necessary to go back to older versions to bring back functionality that was removed unintentionally or to restore something that stopped working after changes were made. This recipe shows you how to view a file and a project's history, see all changes that occurred between two versions of a file, and restore a version of a file older than the last commit operation.

Getting ready

You should have already installed a Subversion client, created a local repository, imported and checked out files, as well as performed at least two commit operations, before performing the steps in this recipe. These steps will be slightly different based on the Subversion client that you have selected and the operating system that you are using.

How to do it...

  1. 1. Navigate to the WordPress plugin directory of your local installation in the file explorer if you are not already there.

  2. 2. Right-click on the hello.php file and select the TortoiseSVN | Show log menu item. This command displays a chronological listing of all modifications to this file, starting from its initial import to the repository.

  3. 3. Right-click on the oldest revision available for the file and select the Compare with working copy menu item. A diff view of the selected version of the file compared to the current working version will be displayed on-screen.

  4. 4. Right-click on the oldest revision available for the file and select the Revert to this revision menu item. Confirm the request by selecting the Revert option. The hello.php plugin file will revert back to the state it was in at the time of its initial import to the repository.

  5. 5. Right-click in an empty area of the file explorer and select the TortoiseSVN | Show Log menu item. The resulting dialog shows a chronological listing of all import and commit operations, indicating the dates when each action occurred and displaying the messages that were associated to each of them. It also displays a listing of all files that were involved in each action.

  6. 6. Click on each entry in the revision list to see the files that were affected and the type of operation that was performed on each of them.

  7. 7. Find the revision where the index.php file was deleted from the plugin directory.

  8. 8. Right-click on the index.php file and select Revert changes from this revision to restore the file. Select the Revert option to confirm the request.

How it works...

The Subversion client connects to the repository to generate a full history log for the selected file or directory. It will then traverse all information stored during all import and commit operations to produce a full listing. Since a Subversion repository keeps track of all versions of files along with the messages that were stored with each operation, it can easily show how files change during a project's history or restore a file to a previous state.

Of course, this flexibility comes at a price since all of these file versions use space on the hard drive that hosts the repository. However, this is a small price to pay for the peace of mind of having easy access to organized versions of files over the lifetime of a project.

 

Installing a dedicated code/text editor


Most operating systems provide a built-in text editor. While it is possible to create WordPress plugins using such a simple tool, it is highly recommended to install a dedicated code editor on your computer to simplify your plugin development work.

Of course, not all code editors are equal. Here are some of the features that you should look for when selecting a code editing application:

  • PHP syntax highlighting

  • Completion of PHP function names

  • Ability to search in multiple files simultaneously

  • Ability to highlight all instances of search keyword(s) or selected text

  • Line numbering

  • Ability to resize the editor text or specify a replacement font

  • Possibility of opening multiple files simultaneously

The following free editors contain most or all of these key features:

This recipe explains how to install a dedicated code editor and shows basic editor operations. It provides detailed steps using Programmer's Notepad for Windows.

How to do it...

  1. 1. Download the installation package for one of the text editors listed previously.

  2. 2. Run the installation program for the editor and select the default settings.

  3. 3. Launch the text editor.

  4. 4. Open the hello.php file from the plugin directory of your local WordPress installation. You will see that different parts of the code are displayed in different colors based on the type of code.

  5. 5. Double-click on a word to select it. You will see any other instance of that same word highlighted across the file contents.

  6. 6. Select the View | Line Numbers menu item (or similarly named item based on your selected text editor) to display line numbers in the editor.

How it works...

Code editors have built-in parsers that enable them to identify the parts of the code that are comments, PHP language functions, text strings, and a variety of other elements. Having these elements colored on-screen makes it much easier to read through code and to see that a function's name is not spelled correctly, or to quickly identify comments.

Another functionality that is crucial when developing plugins for WordPress is the ability to see line numbers in the editor. This function comes in handy especially when PHP code errors come up, since the filename and line of code that was being processed at the time of the error are normally displayed. In most code editors, the developer can either scroll to the specific line or enter the line number in a quick Go To dialog box to jump to that line right away.

 

Installing and configuring the NetBeans Integrated Development Environment


If you have enjoyed moving to a dedicated code editor in the previous recipe but want a solution that provides even more integration to perform all of your WordPress plugin development tasks in a single place, an integrated development environment (IDE) such as the free NetBeans platform will be the perfect solution for you. In addition to having all of the core features of a code editor, NetBeans has the ability to constantly parse your code to identify syntax errors and highlight changes made since your last commit or update operation, right in the editor.

It also features built-in Subversion and MySQL clients to be able to commit code changes and manage database records straight from its interface. The NetBeans application is cross-platform, available on the Windows, Mac, and Linux operating systems, and can be quickly configured to work with a local WordPress installation. This recipe explains how to perform these installation and configuration tasks.

Getting ready

You should already have set up a local WordPress installation on your computer.

How to do it...

  1. 1. Download the PHP NetBeans installer for your choice of platform from the NetBeans website http://netbeans.org/downloads/index.html).

    Note

    While you can choose a version of NetBeans that will support a large variety of programming languages (Java, C/C++, and so on), the PHP version of NetBeans contains all the necessary elements to develop plugins for WordPress.

  2. 2. Install the NetBeans tool by running the installer, selecting all default options, and accepting the license agreement.

  3. 3. Launch the NetBeans IDE using the shortcut it created during the installation.

  4. 4. Install the latest updates, if applicable, and restart the IDE to run the latest version.

  5. 5. Select the File | New Project menu item.

  6. 6. Select PHP in the Categories section and PHP Application with Existing Sources in the Projects section.

  7. 7. Click on Next.

  8. 8. Set the Sources Folder to the location of your local WordPress installation (c:\WPDev on Windows, if you followed the previous recipe).

  9. 9. Specify a Project Name (for example, WordPress Development Site).

  10. 10. Select PHP 5.3 in the PHP Version field.

  11. 11. Check the Put NetBeans metadata into a separate directory option and create a new folder to hold this data (for example, c:\WPNetBeansData).

  12. 12. Click on Next.

  13. 13. Set the Project URL to http://localhost/.

  14. 14. Click on Finish.

  15. 15. Once the project is loaded, close the Tasks panel since it will be populated with a long list of to-do tasks that are extracted from the WordPress source code.

  16. 16. Using the Projects view, navigate to the wp-content/plugins directory of your WordPress installation and double-click on the hello.php file to see it in the NetBeans editor.

  17. 17. Search for the keyword function in the file and remove its last letter n to see a red exclamation mark displayed in the left margin of the code editor. This indicates that a PHP syntax error was detected.

  18. 18. Undo this last change.

  19. 19. Press the F6 key to launch a web browser session pointing to your local development site.

How it works...

The NetBeans editor works by creating a project that points to your website's directory structure and loading all files that are found in that location. With its integrated project browser, it is very easy to find and edit multiple plugin files by starting a single tool. NetBeans combines all of the functionality of a dedicated code editor, a Subversion client such as TortoiseSVN, and the phpMyAdmin database administration interface to make it possible to perform all tasks related to WordPress plugin development in a single environment.

See also

  • Interacting with a Subversion repository from the NetBeans interface recipe

 

Interacting with a Subversion repository from the NetBeans interface


One of the multiple benefits of using the NetBeans IDE is that it is pre-integrated with the Subversion version control system. Whether you're developing plugins for your own private use, for customers, or for public distribution on wordpress.org, Subversion is a great system to use to keep track of all important revisions of your work over time.

This recipe explains how to use the built-in Subversion functionality in NetBeans to interact with a file repository.

Getting ready

You should have already installed the NetBeans IDE and created a project pointing to your local WordPress development site. You should also have created a Subversion repository on your system and imported the contents of the WordPress plugin directory.

Note

At the time of writing, an incompatibility between NetBeans 7.1 and repositories created by TortoiseSVN 1.7.x requires additional steps to be executed before performing this recipe. These steps can be found on the Netbeans website at http://netbeans.org/projects/versioncontrol/pages/Subversion1_7.

How to do it...

  1. 1. Using the Projects view in NetBeans, navigate to the wp-content/plugins directory of your WordPress installation and double-click on the hello.php file to display it in the code editor.

  2. 2. Change any line of code in the plugin header (top section of the plugin information on the plugin name, author, and so on). Notice that colored bands start appearing on the left margin of the code editor as lines are modified, added, or deleted.

  3. 3. Position the mouse cursor over the colored area that is displayed next to the modified line to see a tooltip indicating that the line has been modified.

  4. 4. Click on the colored notification area to see the previous content of that line and have the opportunity to roll back the modified content to its last known state from a previous insert, commit, or update operation.

  5. 5. In the project window, right-click on the hello.php file and select the Subversion | Commit menu. This command displays the NetBeans Subversion Commit interface. While it is slightly different from the equivalent TortoiseSVN dialog, you should still recognize the field used to specify a commit message and the list of all files that were identified as having changed from the last insert, commit, or update operation.

  6. 6. Enter a message in the Commit Message field.

  7. 7. Click on the Commit button to send your changes to the Subversion repository.

    Note

    By right-clicking on any file from the plugin directory and selecting the Subversion menu, we can see that all the functionalities we explored in the previous Subversion-related recipes are available in the NetBeans environment. However, some of them have different names. For example, the Show log menu item is called Search History and has some more advanced features than the TortoiseSVN client.

How it works...

Similar to the way the TortoiseSVN client works, the NetBeans interface has been built using the Subversion client libraries to provide us with a full-featured tool that can access any Subversion repository. Since our WordPress plugin directory files were already imported and checked out from a repository, NetBeans is able to read the repository information that is contained in the .svn directories located across the project structure and use this data to identify code changes on the fly during code editing. It also has access to information on the repository address that is associated to the plugin files to send new and updated items to the correct location without asking us to specify where they should be sent.

 

Managing a MySQL database server from the NetBeans interface


With its built-in MySQL interface, the NetBeans IDE allows us to perform database queries, data updates, and table structure modifications from the same interface that we will use to write our WordPress plugins. This recipe will show you how to get NetBeans to connect to your local MySQL database server and access data from some of the WordPress data tables.

Getting ready

You should have already installed a local web server on your computer, completed a local WordPress installation, set up the NetBeans IDE, and created a project pointing to your local WordPress development site.

How to do it...

  1. 1. Click on the Services tab on the left side of the NetBeans interface.

  2. 2. Expand the Databases item in the navigation tree.

  3. 3. Expand the Drivers item.

  4. 4. Right-click on the MySQL (Connector/J driver) item and select the Connect Using... menu item.

  5. 5. Leave the Host field with its default value (localhost).

  6. 6. Change the Database name to wordpressdev.

  7. 7. Leave all other fields as they are.

  8. 8. Click on the Test Connection button. This will try to connect to the MySQL database server and will display a message indicating if the connection was successful.

  9. 9. Click on the Finish button to complete the connection setup.

  10. 10. Expand the new jdbc:mysql://localhost:3306/wordpressdev [root on Default schema] item that appeared below Drivers.

  11. 11. Expand the wordpressdev item.

  12. 12. Expand the Tables item.

  13. 13. Expand the wpdev_posts table element to see a list of all fields in the WordPress posts table.

  14. 14. Right-click on the wpdev_posts table and select the View Data... menu item to show all data records contained in this table. As you can see, posts and pages are actually stored in the same database table. In addition to displaying the requested data, NetBeans also shows the SQL query that it performed to retrieve the data. This can be useful to learn the basics of this query language.

How it works...

The NetBeans IDE has been compiled with the necessary client libraries to connect to a MySQL database. By configuring NetBeans to access our database, it is able to get information on the complete information structure and present us with an interface that is much more dynamic than the phpMyAdmin web-based interface that was shown in a previous recipe.

Being aware of the structure of a WordPress database and learning the syntax of SQL commands will help you greatly as we start developing plugins in the later recipes.

About the Author

  • Yannick Lefebvre

    Yannick Lefebvre is a plugin developer who has created multiple plugins on the official WordPress repository. His first creation, Link Library, is in use on thousands of sites around the world. With a background in Computer Science, he started writing plugins for his own WordPress site in 2004 and quickly started sharing his creations with the community. He is actively involved in the Montreal WordPress community, has presented multiple times at WordCamp Montreal and offers custom plugin development services. By day, Yannick works for CM Labs Simulations, a company providing software tools and simulators for vehicle and heavy equipment simulation. You can find out more about him and his plugins on his web site, Yannick's Corner.

    Browse publications by this author
Book Title
Access this book, plus 7,500 other titles for FREE
Access now