Packt Publishing

And you will do all of these by developing a Post Types plugin that provide pre-defined post templates to add a photo or a link quickly to your blog.

The concepts you will learn in this article will help you discover the not so obvious capabilities of the WordPress platform that allows you to transform it into software—capable of handling much more than just a blog.

Handling localization

Localization is an important part of WordPress development as not everyone using WordPress speaks English (WordPress comes in different languages too).

Localization involves just a small amount of the extra work on your side, since the translation itself is usually done by volunteers (people who like and use your plugin).

You only need to provide some base files for translation, and don't be surprised when you start getting translated files sent to your inbox.

WordPress uses the GNU gettext localization framework, which is a standardized method of managing translations, and we will make use of it in our plugin.

Time for action – Create plugin and add localization

We will start by defining our plugin as usual, and then add localization support.

Since loading the file takes resources, we will load it only when the translation is actually needed by checking the current page ($pagenow) and the list of pages pages where we need translations ($local_pages array):

Then it creates the language file name by adding together the plugin dir, plugin folder, and the lang folder where we will keep the translations. The file name is derived from the locale, and the *.mo language file extension:

Finally, the localization file is loaded using the load_textdomain() function, taking our text domain and .mo file as parameters.

// load translationload_textdomain($this->plugin_domain, $mofile);

Optimizing localization usage

The translation file needs to be loaded as the first thing in the plugin—before you output any messages. So we have placed it as the first thing in the plugin constructor.

Since loading the translation file occurs at the beginning of the constructor, which is executed every time, it is a good idea to select only the pages where the translation will be needed in order to preserve resources.

WordPress provides the global variable, $pagenow, which holds the name of the current page in use.

We can check this variable to find out if we are on a page of interest. In the case of plugin activation error message, we want to check if we are on the plugins page defined as plugins.php in WordPress:

You can optimize this further by querying the page parameter, if it exists, as this will—in most cases—point precisely to the usage of your page (plugins.php?page=photo):

if ($_GET['page']=='photo')

Optimizing the usage of the translation file is not required; it's just a matter of generally loading only what you need in order to speed up the whole system.

How does localization work?

For localization to work, you need to provide .po and .mo files with your plugins. These files are created by using external tools such as PoEdit.

These tools output the compiled translation file, which can be then loaded by using the load_textdomain() function. This function accepts a language domain name and a path to the file.

In order to use translated messages, you can use the __($text, $domain) and _e($text, $domain) functions. The _e() function is just an equivalent of

echo __();

These functions accept two parameters, the first being the desired text, and the second, the language domain where the message will be looked for.

If no translation was found, the text is just printed out as it is. This means that you can always safely use these functions, even if you do not provide any translation files. This will prepare the plugin for future translation.

Quick reference$pagenow: A global variable holding the name of the currently displayed page within WordPress.get_locale(): A function which gets the currently selected language.load_textdomain(domain, filepath): This function loads the localization file and adds it to the specified language domain identifier._(); _e(): These functions are used to find the output text using a given language domain.More information about WordPress localization is available at: http://codex.wordpress.org/Translating_WordPress.

Adding a post template

Our next goal is to add a simple post template to the WordPress Write page.

The purpose of a custom post template is to handle writing a quick post in case we don't need the whole Write Post interface, for reasons of speed or customization.

The great thing about post templates is that they can be customized to accept any information you want—for example, job portal listings or inventory items.

Let's start with a simple Add Photo template where we want to be able to just set the title, specify a photo and publish immediately.

Time for action – Create 'add photo' post template

In order to create the post template, we need a place for it in the menus. We will use the Write menu and place a submenu there:

The function does not process any information yet; it just prints out the template.

The end result is our new post template in the Write menu.

What just happened?

We have just created a quick photo post template. For the sake of simplicity, the form has been designed to have only three fields.

When creating a backend form, you can design it any way you want, but you can also decide to use the WordPress CSS classes. If you go for WordPress classes, your forms will blend into the backend and look more professional.

Backend CSS classes

The standard classes of WordPress Backend CSS (up to version 2.6) use wrap for displaying forms, and use poststuff to create the wrapper

submitbox is the right-hand side column with the Publish button that contains extra classes such as previewview and inside, and the button itself is of the class, submit:

The wp_handle_upload() function handles everything for our file, including moving it to the upload directory and setting correct permissions. So, we do not need to worry about it. It also returns a reference to the newly created file, which contains useful information such as the new filename and a URL to the file, which we will need for displaying the photo.

In the next piece of code back in the main function, we will create a thumbnail of the uploaded image to show it in the post and link it to the original picture.

We use the WordPress image_make_intermediate_size() function, which accepts the filename and resizing information as parameters. We chose to use the medium size, which is already defined in the WordPress backend; height and width are stored in the medium_size_h and medium_size_w options, respectively.

Settings for the upload folder (Uploading) and Image sizes can be found on the WordPress Miscellaneous Settings page:

We also need to handle cases where the picture is specified by a URL, in which case we will just use the provided information:

After we have done this, all new photos will turn up in the in the WordPress Media Library (Manage Media) looking like this:

Quick referencewp_handle_upload(&$file, $overrides): A function which handles user uploaded files. Takes information provided by the $_FILES[] variable and the desired overrides (test_form, test_type, test_size).file_is_displayable_image($file): It checks if the file is an image that WordPress can display.wp_upload_dir(): A function which returns the path to the WordPress uploads folder.image_make_intermediate_size($file, $width, $height, $crop=false): A function which resizes the image and returns the new file metadata.add_post_meta($post_id, $meta_key, $meta_value, $unique): The function used to add a custom field to the specified post. The field is identified with a key ($meta_key) and its value ($meta_value).wp_insert_attachment($attachment, $filename, $parent_post_id): This function inserts an attachment for a post, into the Media Library. More information can be found at: http://codex.wordpress.org/Function_Reference/wp_insert_attachmentwp_update_attachment_metadata($post_id, $data): This function updates attachment metadata, usually used in conjunction with wp_generate_attachment_metadata.wp_generate_attachment_metadata($attachment_id, $file): This function generates the post Image attachment Metadata.

Using custom fields

Custom fields are used in WordPress to store additional information about a post. They are normally available to you in the Write Post screen as Key/Value pairs.

You can use custom fields to display information on the site or for some other kind of special processing (like storing a post's expiration date).

Adding custom fields

To add a custom field from the code, you can use the add_post_meta() function:

add_post_meta($post_id, $meta_key, $meta_value, $unique)

post_id: This parameter contains the ID of the post where the custom field is to be added.

meta_value: This parameter contains the value for the key (such as happy,temporarily, and so on).

unique: This parameter contains is used to decide whether you want this key to be unique. WordPress supports multiple values for the same key, and if the value set is unique, only one instance for the given key is allowed.

prev_value: This contains the previous value of the key, which helps us to differentiate the values if the key is not unique.

To update existing fields, you can use the update_post_meta() function:

update_post_meta($post_id, $meta_key, $meta_value, $prev_value)

Retrieving custom fields

To retrieve custom fields, you can use one of the following functions:

get_post_custom($post_id): This function returns a multidimensional array with all the custom fields of a particular post or page.

get_post_custom_keys($post_id): This function returns an array containing the keys of all custom fields of a particular post or page.

get_post_custom_values($key, $post_id): This function gets the list of values for a particular key on the current post.

get_post_meta($post_id, $key, $single = false): This function gets the value for the specified key in a given post. If $single is true, then only the first key is returned (even if there are more).

This piece of code will cause the Manage, Design, and Comments pages to disappear from the WordPress main menu leaving with only the with Write menu:

Similarly, we remove the Link page from the submenus:

// remove 'Link' from Write menuunset($submenu['post-new.php'][15]);

Using the menu arrays, you can customize the backend of a WordPress site to show only relevant information for your purpose. If you are turning WordPress into a CMS, implementing custom fields and tinkering with menus would be the first things on the list.

Summary

The purpose of the Post Types plugin was to introduce you to different aspects of WordPress backend development.

While creating our different Post Types, we have learned how to customize WordPress menus to our liking. We used custom fields to insert important information to the post which we do not want to be visible in the post content.

Here are the most important lessons from this article:

Localization: Not everyone uses WordPress in English

Backend CSS classes: Use them to make your forms prettier

Custom fields: They are the powerhouse behind WordPress CMS capabilities

Customize Menus: Your plugin can choose the menus in the WordPress backend

Alerts & Offers

Series & Level

We understand your time is important. Uniquely amongst the major publishers, we seek to develop and publish the broadest range of learning and information products on each technology. Every Packt product delivers a specific learning pathway, broadly defined by the Series type. This structured approach enables you to select the pathway which best suits your knowledge level, learning style and task objectives.

Learning

As a new user, these step-by-step tutorial guides will give you all the practical skills necessary to become competent and efficient.

Beginner's Guide

Friendly, informal tutorials that provide a practical introduction using examples, activities, and challenges.

Essentials

Fast paced, concentrated introductions showing the quickest way to put the tool to work in the real world.

Cookbook

A collection of practical self-contained recipes that all users of the technology will find useful for building more powerful and reliable systems.

Blueprints

Guides you through the most common types of project you'll encounter, giving you end-to-end guidance on how to build your specific solution quickly and reliably.

Mastering

Take your skills to the next level with advanced tutorials that will give you confidence to master the tool's most powerful features.

Starting

Accessible to readers adopting the topic, these titles get you into the tool or technology so that you can become an effective user.

Progressing

Building on core skills you already have, these titles share solutions and expertise so you become a highly productive power user.