learn more...Social Bookmarking with WordPress Plugin In this article by Vladimir Prelovac, we will learn to create our first functional WordPress plugin and learn how to interact with the WordPress API (this is the WordPress interface to PHP) on the way. The knowledge you will gain in this article alone will allow you to write a lot of similar plugins. This article is extracted from the "WordPress Plugin Development" book. Let's get moving! In this article, you will learn:
{literal} You will learn these by creating a Social Bookmarking type of plugin that adds a Digg button to each post on your blog
As you probably know, Digg is a very popular service for promoting interesting content on the Internet. The purpose of a Digg button on your blog is to make it easier for Digg users to vote for your article and also to bring in more visitors to your blog. The plugin we'll create in this article will automatically insert the necessary code to each of your posts. So let's get started with WordPress plugin development! Plugging in your first pluginUsually, the first step in plugin creation is coming up with a plugin name. We usually want to use a name that is associated with what the plugin does, so we will call this plugin, WP Digg This. WP is a common prefix used to name WordPress plugins. To introduce the plugin to WordPress, we need to create a standard plugin header. This will always be the first piece of code in the plugin file and it is used to identify the plugin to WordPress. Time for action - Create your first pluginIn this example, we're going to write the code to register the plugin with WordPress, describe what the plugin does for the user, check whether it works on the currently installed version of WordPress, and to activate it.
What just happened?We created a working plugin template by using a plugin information header and the version check code. The plugin header allows the plugin to be identified and displayed properly in the plugins admin panel. The version check code will warn users of our plugin who have older WordPress versions to upgrade their WordPress installation and prevent compatibility problems. The plugin information headerTo identify the plugin to WordPress, we need to include a plugin information header with each plugin. The header is written as a PHP comment and contains several fields with important information. This code alone is enough for the plugin to be registered, displayed in the admin panel and readied for activation. If your future plugin has more than one PHP file, the plugin information should be placed only in your main file, the one which will include() or require() the other plugin PHP files. Checking WordPress versionsTo ensure that our plugin is not activated on incompatible WordPress versions, we will perform a simple WordPress version check at the very beginning of our code. WordPress provides the global variable $wp_version that provides the current WordPress version in standard format. We can then use PHP function version_compare() to compare this and our required version for the plugin, using the following code: if (version_compare($wp_version,"2.6","<")) If we want to stop the execution of the plugin upon activation, we can use the exit() function with the error message we want to show. In our case, we want to show the required version information and display the link to the WordPress upgrade site. $exit_msg='WP Digg This requires WordPress 2.6 or newer. <a While being simple, this piece of code is also very effective. With the constant development of WordPress, and newer versions evolving relatively often, you can use version checking to prevent potential incompatibility problems. The version number of your current WordPress installation can be found in the footer text of the admin menu. To begin with, you can use that version in your plugin version check (for example, 2.6). Later, when you learn about WordPress versions and their differences, you'll be able to lower the version requirement to the minimal your plugin will be compatible with. This will allow your plugin to be used on more blogs, as not all blogs always use the latest version of WordPress. Checking the pluginYou can go ahead and activate the plugin. The plugin will be activated but will do nothing at this moment. Time for Action - Testing the version check
What just happened?The version check fails and the plugin exits with our predefined error message. The same thing will happen to a user trying to use your plugin with outdated WordPress installation, requiring them to update to a newer version. Have a go HeroWe created a basic plugin that you can now customize.
Displaying a Digg buttonNow it's time to expand our plugin with concrete functionality and add a Digg link to every post on our blog. In order to create a link we will need to extract post's permalink URL, title, and description. Luckily, WordPress provides us with a variety of ways to do this. Time for Action - Implement a Digg linkLet's create a function to display a Digg submit link using information from the post.
Well done! You have created your first working WordPress plugin! What just happened?When WordPress loads a post, the single.php template file from the currently active WordPress theme is ran. We added a line to this file that calls our plugin function WPDiggThis_Link() just after the content of the post is displayed: <?php the_content('<p class="serif">Read the rest of this entry
We use function_exists() to check our function because it exists only if our plugin is installed and activated. PHP will generate an error if we try to run a nonexistent function. But if we deactivate the plugin later, we don't want to cause errors with our theme. So, we make sure that the function exists before we attempt to run it. Assuming that the plugin is present and activated, the WPDiggThis_Link() function from our plugin is ran. The first part of the following function gets information about our post and assigns it to variables: /* Show a Digg This link */ We use the urlencode() PHP function for all the parameters that we will pass to the final link. This will ensure that all the values are formatted properly. The second part uses this information to construct a Digg submit link: // create a Digg link and return it It returns this HTML text so that it gets added to the WordPress output at the point where the function is called - just after the post is displayed. Therefore, the link appears right after each post-which is convenient for the user who has just finished reading the post. Using the Digg APIUsually, when using the functionalities of third-party sites, as we are doing in our example with Digg, we would search for the API documentation first. Almost all the major sites have extensive documentation available to help developers use their services in an effective way. Digg is no exception, and if you search the Internet for the digg button api you will find a page at http://digg.com/tools/integrate that will have all the details we need in order to implement our Digg functionality. Digg allows us to use several different ways of using their service.
For the start, we will display just a Digg link. Later, we will expand it and also display a normal button. Here is what the Digg documentation says about formatting a submit link. Submit URL:http://digg.com/submit?url=example.com&title=TITLE&bodytext=DESCRIPTION&media=MEDIA&topic=TOPIC Submit URL Details:
Using this information, we are able to create a valid link for the Digg service from the information available in our post. Acquiring post informationWordPress provides a number of ways to get information about the current post. One of them involves using the global variable $post, which stores all the relevant information for the current post. We have used it in our example to extract the post title and content, but it can also be used to get other information such as post category, status and so on. WordPress also offers an array of functions we could have used to access post information such as get_the_title() and get_the_content(). The main difference between using these functions and accessing post data directly using $post variable is in the end information we get. The $post variable contains raw information about the post, just as the user wrote it. The functions mentioned above take the same raw information as a starting point, but could have the final output modified by external factors such as other active plugins. You can browse through the wp-includes/post-template.php file of your WordPress installation to get a better understanding of the differences between using the $post variable and the WordPress provided functions. Post permalink URLIn order to obtain post URL we used the get_permalink() WordPress function. This function accepts the post ID as a parameter, and as a result, returns post's actual URL on the blog. It will always return a valid URL to your post no matter what permalink structure your blog is using. Editing the theme filesIn our example, we had to edit our theme in order to place the Digg link under the post content. WordPress allows for easy theme editing through the built-in Theme Editor panel. After selecting the theme you want to edit, you will be presented with a number of options. Every theme consists of various PHP template files, each covering different blog functionalities. Here is a reference table detailing the most commonly used template files.
Always be careful when editing the theme files as any kind of mistake in your syntax can cause an error in displaying the page. It is therefore good practice to first backup theme files, so you can safely revert to them afterwards. Quick reference Have a go HeroOur plugin already has useful functionality. Try to customize it by:
WordPress plugin hooksOur plugin now works fine, but there is a problem. In order to use it, we also have to edit the theme. This can be a real pain for all sorts of reasons:
We need some way to make the plugin work on its own, without the users having to change their themes or anything else. Hooks come to the rescue, making it possible to display our Digg This button in our posts-without ever modifying our theme. Time for Action - Use a filter hookWe will use the the_content filter hook to automatically add our Digg This link to the end of the post content. This will avoid the need for the users to edit their theme files if they want to use our plugin.
The end result is now the same, but we now control the appearance of the link directly from our plugin. What just happened?When we activate our plugin now, WordPress comes across and runs this line: add_filter('the_content', 'WPDiggThis_ContentFilter');
This tells WordPress that every time it's going to display the content of a post or page, it should run it through our WPDiggThis_ContentFilter() function. We don't need to modify the theme file anymore - WordPress will make sure that the function runs at the required time. When we load a post now, WordPress will automatically call our function: /* Add Digg link to the end of the post */ This function receives the post's content as a parameter, and returns the filtered content. In this case, our Digg link gets automatically appended to the end of the content. WordPress hooksWordPress provides a powerful mechanism for plugin functions to be called at the exact time when we need them. This functionality is accomplished by using the so called hooks. Every time you call a page from your browser, the WordPress engine goes through every possible function it needs to render the requested page. Somewhere along the way, you can "hook" up your function and use it to affect the end result. You do this by simply registering your function with a specified hook, allowing it to be called by WordPress at the right moment. There are two types of WordPress hooks:
Filter hooksWe learned that filter hooks (also referred to as simply 'filters') are functions that process WordPress content, whether it is about to be saved in the database or displayed in the user's browser. WordPress expects these functions to modify the content they get and return it. In our case, we used the_content filter hook to modify the post content by appending a Digg link to it. We could also have placed the Digg link at the beginning of the post, or broken up the post and put it in the middle. To set up a filter, we need to use the add_filter function: add_filter ( 'filter_hook', 'filter_function_name' , [priority],
Here is an example list of filter hooks, which will help you to get a better understanding of what you can achieve using them.
Filter hooks can be removed using the remove_filter() function. It accepts the same arguments as add_filter(), and is useful if you want to replace some of the existing WordPress filters with your functions. If you want to take a closer look at the default WordPress filters, you can find them in the wp-includesdefault-filters.php file of your WordPress installation. It is important to remember that the filter function always receives some data and is responsible for returning the data, whether it modifies the data or not. Only if you want to disregard this data completely, can you return an empty value. Action HooksWe use action hooks when we need to include specific functionalities every time a WordPress event triggers, for example when the user publishes a post or changes the theme. WordPress does not ask for any information back from the action function, it simply notifies it that a certain event has happened, and that a function should respond to it in a desired way. Action hooks are used in a way similar to the filter hooks. The syntax for setting up an action hooks is: add_action ( 'action_hook', 'action_function_name', [priority],
The following table presents example action hooks provided by WordPress.
Just as with filters, you can use the remove_action() function to remove currently registered actions. Practical filters and actions examplesSince understanding the power of filters and actions is very important for conquering WordPress plugin development, we will now examine a few more simple examples of their usage. Upper case titlesThe hook function can be any registered function. In this case, we will pass the title of the post to strtoupper making all titles appear in upper case. add_filter('the_title', strtoupper);
Mailing listActions provide a very powerful mechanism for automating tasks. Here is how to send a notification to a mailing list whenever there is an update on your blog. function mailing_list($post_ID) Changing core WordPress functionalitySometimes you may not be satisfied with the default WordPress functionalities. You may be tempted to modify the WordPress source code, but you should never do that. One of the main reason is that when you upgrade to a new version of WordPress the upgrade process could overwrite your changes. Instead, try whenever possible to write a plugin and use actions and filters to change the desired functionality. Let's say we want to change WordPress post excerpt handling. WordPress uses the wp_trim_excerpt() function with the get_the_excerpt filter responsible for processing the post excerpt. No problem, let's replace it with our own function, using the WordPress function as a starting point. /* Create excerpt with 70 words and preserved HTML tags */ These were just a few practical examples. You can do almost anything that crosses your mind using action and filter hooks in WordPress. Sometimes, you can achieve the same result by using either the action or the filter hook. Quick reference Have a go HeroOur filter function now controls the behaviour of a Digg link. Try these exercises:
Adding a Digg button using JavaScript codeOur Digg link works fine for submitting the content, but isn't very pretty, and does not show the number of Diggs we received. That is why we need to use a standard Digg button. This is accomplished by using a simple piece of JavaScript code provided by Digg, and passing it the necessary information. Time for Action - Implement a Digg buttonLet us implement a Digg button, using information from the Digg API. We will use the newly created button on single posts, and keep the simple Digg link for all the other pages.
What just happened?WordPress will parse our content filter function according to the conditional statement we have added: function WPDiggThis_ContentFilter($content) This means that if the current viewed page is a single post or page, we will append our Digg button at the beginning of that post. If we are viewing all the other pages on the blog (like for example the home page or archives) we will show the Digg This link instead. if (is_single() || is_page()) The reason for doing so is that we do not want to clutter the home page of the blog with a lot of big yellow Digg buttons. So we just place a subtle link below the post instead. On single pages, we show the normal button using our new WPDiggThis_Button() function. The first part is similar to our previous WPDiggThis_Link() function, and it acquires the necessary post information. /* Return a Digg button */ However in this case, we are treating all the information through the js_escape() WordPress function, which handles formatting of content for usage in JavaScript code. This includes handling of quotes, double quotes and line endings, and is necessary to make sure that our JavaScript code will work properly. We then create a code using Digg API documentation for a JavaScript button: // create a Digg button and return it Conditional TagsWe have used two functions in our example, is_single() and is_page(). These are WordPress conditional tags and are useful for determining the currently viewed page on the blog. We used them to determine if we want to display a button or just a link. WordPress provides a number of conditional tags that can be used to control execution of your code depending on what the user is currently viewing. Here is the reference table for some of the most popular conditional tags.
Conditional tags are used in a variety of ways. For example, is_single('15') checks whether the current page is a single post with ID 15. You can also check by title. is_page('About') checks if we are on the page with the title 'About'. Quick reference Styling the outputOur Digg button looks like it could use a better positioning, as the default one spoils the look of the theme. So, we will use CSS to reposition the button. Cascading Style Sheets or CSS for short (http://www.w3.org/Style/CSS/) are a simple but powerful tool that allows web developers to add different styles to web presentations. They allow full control over the layout, size, and color of elements on a given page. Time for Action - Use CSS to position the buttonUsing CSS styles, we will move the button to the right of the post.
What just happened?We used CSS to move the button to a desired position. CSS is extremely useful for these kinds of tasks and is commonly used in WordPress development to enhance the user experience. // encapsulate the button in a div We have basically encapsulated our button in a <div> element and forced it to the right edge by using float: right CSS command inside a style tag. We could further experiment with the placement of the button until we find the most satisfying solution. For example, if we hook to the_title filter instead of the_content, and moved the button to the left , we would get the following result:
Certainly, having good CSS skills is a very valuable asset in WordPress plugin development. Have a go HeroNow that our button is finished, there are a lot of possible customizations you can make to the look or position of your button, using both built-in Digg options and CSS.
SummaryIn this article, we created a working, useful, and attractive WordPress plugin from scratch. Our plugin now displays a fully functional Digg button. We learned how to extract information using WordPress API and how to use CSS to improve the appearance of our plugin. We also investigated some more advanced WordPress functionalities such as hooks. Specifically, we covered:
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Disclaimer
1) E-articles is not responsible for the information contained by this article as well for any and all copyright infringements by authors and writers. E-articles is a free information resource. If you suspect this article for any copyright infringement, please read the terms of service and contact us to investigate the problem.
2) E-articles is not responsible for inaccuracies, falsehoods, or any other types of misinformation this article may contain and will not be liable for any loss or damage suffered by a user through the user's reliance on the information gained here. link to this article |