plugin_development   26

Building the Favorite Plugins Plugin
Now that it’s possible to favorite plugins on, wouldn’t it be great to be able to make your favorites available for speedy install from within the WordPress dashboard? Let’s build a plugin to do just that!
Finding Your Favorite PluginsMost of us who use WordPress have, at some time or another, trawled through the plugin directory looking for a plugin to add a particular piece of functionality to a website. Often there’s more than one option, and it can take a little time to asses which is the one that does the job best. Perhaps after a while, you have a handful of plugins you use on every install, and maybe a few that you really like for specific tasks. How do you keep track of them? Do you just search the plugin directory every time?
Not too long ago the favorites feature was released on, so now you can mark certain plugins as ‘favorites’, allowing you to easily find them from your profile. This is an excellent start to keeping track of them.
Even more recently, a new argument was added to the Plugin API to search for plugins favorited by a specific user. So now it would be possible to write a plugin to bring this functionality into the WordPress dashboard.
I wrote a plugin called ‘Favorite Plugins‘, and I’m going to walk you through building it now.
Note: This functionality is actually going to be a part of WordPress when version 3.5 is released in December. We’re building this plugin as an exercise in plugin building, and using the Plugin API.
Step 1 Building the Base of the PluginWhen building a plugin, it’s a good idea to plan things out before you get too far into the nitty gritty of the code. This helps keep you focussed, and saves you writing lines and lines of code, only to realise you’ve got more code than you need and you’ve overcomplicated things.
So here’s what our plugin is going to do:
Add a new tab called ‘Favorites’ to the ‘Install Plugins’ screen in the WordPress adminOn the new tab, we’ll have a form to enter the username to useIf we have a username, we ask for the favorites for that userBelow the form we display a table showing all the favorite plugins for the provided user (if there are any)We’ll also remember the username entered to keep things convenient. After all, that’s what this plugin is all about!Now let’s get our files in order. Create yourself a directory under /wp-content/plugins/ called wptuts-favorite-plugins. Inside this new directory, create yourself a file called wptuts-favorite-plugins.php. Then open the file up and, as always when developing a plugin, add the plugin header as follows:

Plugin Name: Wptuts+ Favorite Plugins
Plugin URI:
Description: Quickly and easily access and install your favorited plugins from, right from your dashboard.
Version: 0.7
Author: Japh
Author URI:
License: GPL2
Now we’ll create the class and stubs for the methods we’re going to use in this plugin. We use a class to build the plugin so we can take advantage of features provided by developing using object-oriented methods, and it also keeps all our functions nicely namespaced.
Here’s the class stub and the methods we’ll need:

class Wptuts_Favorite_Plugins {
public $username = null;
function __construct() {
// The constructor is used to kick things off, as it's run when the object is created
function add_favorites_tab( $tabs ) {
// This is where we put code to add a favorites tab to the.
return $tabs;
function get_favorites() {
// Someone wants to see what's on the favorites tab, so we'd better get some stuff to show them
function install_plugins_favorites() {
// Output the form to accept the username
function wptuts_execute() {
if ( (float) get_bloginfo( 'version' ) < 3.5 ) {
// Kick everything into action...
$wptuts_favorite_plugins = new Wptuts_Favorite_Plugins();
add_action( 'admin_init', 'wptuts_execute' );
That’s it! That’s all the functionality we’re building into this theme. Because we’re building for the WordPress admin, we’re trying to take full advantage of everything that’s done for us.
Also, note that I’ve wrapped the initilisation line in an if statement to stop the plugin working on WordPress 3.5+, which will have this functionality itself anyway.
Step 2 Adding the Favorites TabThis is the quickest and easiest part, so let’s get it done first, and then we can refresh to see any progress as we go through too.
Firstly, we need to add the following code into the __construct method of our class:

add_filter( 'install_plugins_tabs', array( $this, 'add_favorites_tab' ) );
Here we’re hooking onto WordPress’ ‘install_plugins_tab‘ filter which is exactly what we need to add a tab.
What’s that array( $this, 'function_name' ) code doing? As you may be aware, when using object-oriented programming, the $this reserved word is used to refer to the current object. When using hooks in WordPress, the second parameter can be a string with the name of the function to use, or when using an object it can be an array with the object and specific method of the object to use.
Read more about this under Avoiding Function Name Collisions on the WordPress Codex.
Then we make the add_favorites_tab method of our class look like the following:

function add_favorites_tab( $tabs ) {
// This is where we put code to add a favorites tab to the.
$tabs['favorites'] = __( 'Favorites' );
return $tabs;
This simply adds an element to the $tabs array with a value of ‘Favorites’ to be displayed as the tab text. If you go to the ‘Install Plugins’ screen in your WordPress admin now, by clicking on ‘Plugins’ -> ‘Add New’, you’ll see the ‘Favorites’ tab added there. Clicking it now will show you a lovely blank tab. Let’s put some stuff on it.
Step 3 Putting The Form in Our New TabKeep in mind that the tab is ultimately on the same page (‘install_plugins‘) as the other tabs, and this page is actually just waiting for something to do depending on which tab is active. It also has hooks that use the tab name, such as ‘install_plugins_pre_{$tab}‘, and ‘install_plugins_{$tab}‘, both of which we’re going to use.
What this means is that adding the form for the user to enter their username is also relatively simple. Add this line to the __construct method of our class:

add_action( 'install_plugins_favorites', array( $this, 'install_plugins_favorites' ), 10, 1 );
The install_plugins_{$tab} action happens in the body of the tab, and it expects two parameters. The second parameter is for the current page in paginaton. We don’t need pagination for our form, so we supply the callback function and the default priority, and then specify that we’re only going to pass one parameter.
Now we fill out our function to output the form:

function install_plugins_favorites() {
// Output the form to accept the username
$this->username = isset( $_REQUEST['user'] ) ? stripslashes( $_REQUEST['user'] ) : $this->username;
<p class="install-help"><?php _e( 'If you have marked plugins as favorites on, you can browse them here.' ); ?></p>
<form method="get" action="">
<input type="hidden" name="tab" value="favorites" />
<label for="user"><?php _e( 'Your username:' ); ?></label>
<input type="search" id="user" name="user" value="<?php echo esc_attr( $this->username ); ?>" />
<input type="submit" class="button" value="<?php esc_attr_e( 'Get Favorites' ); ?>" />
?>First of all, we’re setting the username to the one submitted through the form, if there is one. Otherwise, we grab the one we already have (we’ll be setting this a little later in the tutorial).
Next we’re providing some text to explain to users what this form is for. In the form, we have a hidden field for the tab value, so that when we submit it we come back to the same tab. The rest is the input field, the username field, and the submit button.
Step 4 We Have a Username, Let’s Get Some FavoritesUsers can submit a form with their username now, but nothing happens… we need to make a request to the Plugin API with the username, and then display the results.
Again we need to add a line to the __construct method of our class to add a method to a WordPress action. This time it’s the install_plugins_pre_{$tab} hook, which runs earlier in the page processing. A good place for an API call.

add_action( 'install_plugins_pre_favorites', array( $this, 'get_favorites' ) );
I guess if we’re calling that method we better make it do something useful:

function get_favorites() {
// Someone wants to see what's on the favorites tab, so we'd better get some stuff to show them
global $wp_list_table;
$this->username = isset( $_REQUEST['user'] ) ? stripslashes( $_REQUEST['user'] ) : $this->username;
if ( $this->username ) {
$args = array( 'user' => $this->username );
update_user_meta( get_current_user_id(), 'wporg_favorites', $this->username );
$api = plugins_api( 'query_plugins', $args );
$wp_list_table->items = $api->plugins;
'total_items' => $api->info['results'],
'per_page' => 24,
} else {
$args = false;
This function also checks is there’s a freshly submitted username, otherwise falls back to a saved one. We then check if the username is empty, because if it is there’s no point making an API request. If the username wasn’t blank, we first update a user meta value with a key of ‘wporg_favorites‘ to be the current username.
We also set a variable called $args to be an array with a key ‘user‘, and a value of the username to find favorites for. This is passed to the plugins_api() function, which we then essentially pass … [more]
Plugins  favorites  plugin_development  WordPress_3.5  from google
october 2012 by Lorikb
A Guide to WordPress Custom Post Types: Creation, Display and Meta Boxes
This entry is part 1 of 2 in the series A Guide to WordPress Custom Post TypeWordPress is built for customization. It was created in such a way that each and every section is customizable. In this tutorial we will be exploring one of the most powerful features of WordPress known as Custom Post Types and how WordPress reached a new height with the advent of this wonderful feature.
What Actually Are Custom Post Types?Suppose you want your blog to have a separate section for Movie Reviews. By using Custom Post Types you can create a new type of item like Posts and Pages, which will contain a different set of data. It will have a new administration menu, dedicated editing pages, custom taxonomies and many more utilities required for full fledged publishing.
Custom Post Types are a new set of administrative options appearing along with the default post types such as Posts, Pages, Attachments etc. A Custom Post Type can store any type of information. It has a dedicated editor, media uploader and uses the existing WordPress table structure for ease in data management. The main advantage of creating custom post types using the WordPress API is that it equips itself well with existing themes and templates. Custom Post Types are also SEO friendly because of their nifty permalinks.
Why Use Custom Post Types?Custom Post Types help us to keep different types of posts in different buckets. It separates our regular posts from others. Simple enough!
Let’s Create a Custom Post Type PluginHere we shall create a custom post type plugin which will display favorite movie reviews. Lets get started.
Step 1: Create WordPress Plugin DirectoryOpen your WordPress Plugin directory and create a new directory called Movie-Reviews.
Step 2: Create PHP FileOpen the directory and create a PHP file named Movie-Reviews.php.
Step 3: Add HeaderOpen the file and add the appropriate header at the top.

Plugin Name: Movie Reviews
Plugin URI:
Description: Declares a plugin that will create a custom post type displaying movie reviews.
Version: 1.0
Author: Soumitra Chakraborty
Author URI:
License: GPLv2
Step 4: Register Custom FunctionBefore the closing of the PHP command, type the following line of code to execute the custom function named create_movie_review during the initialization phase every time a page is generated.

add_action( 'init', 'create_movie_review' );
Step 5: Function ImplementationProvide an implementation of the create_movie_review function.

function create_movie_review() {
register_post_type( 'movie_reviews',
'labels' => array(
'name' => 'Movie Reviews',
'singular_name' => 'Movie Review',
'add_new' => 'Add New',
'add_new_item' => 'Add New Movie Review',
'edit' => 'Edit',
'edit_item' => 'Edit Movie Review',
'new_item' => 'New Movie Review',
'view' => 'View',
'view_item' => 'View Movie Review',
'search_items' => 'Search Movie Reviews',
'not_found' => 'No Movie Reviews found',
'not_found_in_trash' => 'No Movie Reviews found in Trash',
'parent' => 'Parent Movie Review'
'public' => true,
'menu_position' => 15,
'supports' => array( 'title', 'editor', 'comments', 'thumbnail', 'custom-fields' ),
'taxonomies' => array( '' ),
'menu_icon' => plugins_url( 'images/image.png', __FILE__ ),
'has_archive' => true
The register_post_type function does most of the work for us. As soon as it is called it prepares the WordPress environment for a new custom post type including the different sections in the admin. This function takes two arguments: the first one is an unique name of the custom post type and the second one an array demonstrating the properties of the new custom post type. Here it’s another array containing the different labels, which indicates the text strings to be displayed in the different sections of the custom post type e.g. ‘name‘ displays the custom post type name in the dashboard, ‘edit‘ and ‘view‘ are displayed in Edit and View buttons respectively. I think the rest are pretty self explanatory.
In the next arguments:
'public' => true determines the visibility of the custom post type both in the admin panel and front end.'menu_position' => 15 determines the menu position of the custom post type.'supports' => array( 'title', 'editor', 'comments', 'thumbnail', 'custom-fields' ) determines the features of the custom post type which is to be displayed.'taxonomies' => array( '' ) creates custom taxonomies. Here it’s not defined.'menu_icon' => plugins_url( 'images/image.png', __FILE__ ) displays the admin menu icon.'has_archive' => true enables archiving of the custom post type.Please visit the WordPress Codex register_post_type page for more details on the different arguments used in custom post types.
Step 6: Icon for Custom Post TypeSave a 16×16 pixel icon image in your current plugin folder. This is required for the custom post type icon in the dashboard.
Step 7: Activate the PluginActivate the plugin and that’s it, you have a new custom post type which has a text editor, publishing and featured image controls, comment control and the custom fields editor.
Step 8: Add a New ItemClick on the Add New option to go to the custom post type editor. Provide a movie title, a review and set a featured image.
Step 9: PublishPublish the post and click on View Movie Review to view the created movie review in the browser.
Creating Meta Box Fields for Custom Post TypesThe meta box mechanism uses the help of the built in WordPress meta box system and helps to add fields required specifically for the custom post types, without requiring the default custom fields in the editor.
Step 1: Registering the Custom FunctionOpen the Movie-Reviews.php file and add the following code before the PHP end tag. This registers a function to be called when the WordPress admin interface is visited.

add_action( 'admin_init', 'my_admin' );
Step 2: Implementation of the Custom FunctionAdd an implementation of the my_admin function which registers a meta box and associates it with the movie_reviews custom post type.

function my_admin() {
add_meta_box( 'movie_review_meta_box',
'Movie Review Details',
'movie_reviews', 'normal', 'high'
Here add_meta_box is the function used to add meta boxes to custom post types. Explanation of the given attributes:
movie_review_meta_box is the required HTML id attributeMovie Review Details is the text visible in the heading of the meta box sectiondisplay_movie_review_meta_box is the callback which renders the contents of the meta boxmovie_reviews is the name of the custom post type where the meta box will be displayednormal defines the part of the page where the edit screen section should be shownhigh defines the priority within the context where the boxes should showStep 3: Implementation of the display_movie_review_meta_box Function
function display_movie_review_meta_box( $movie_review ) {
// Retrieve current name of the Director and Movie Rating based on review ID
$movie_director = esc_html( get_post_meta( $movie_review->ID, 'movie_director', true ) );
$movie_rating = intval( get_post_meta( $movie_review->ID, 'movie_rating', true ) );
<td style="width: 100%">Movie Director</td>
<td><input type="text" size="80" name="movie_review_director_name" value="<?php echo $movie_director; ?>" /></td>
<td style="width: 150px">Movie Rating</td>
<select style="width: 100px" name="movie_review_rating">
// Generate all items of drop-down list
for ( $rating = 5; $rating >= 1; $rating -- ) {
<option value="<?php echo $rating; ?>" <?php echo selected( $rating, $movie_rating ); ?>>
<?php echo $rating; ?> stars <?php } ?>
This code renders the contents of the meta box. Here we have used an object variable that contains the information of each of the movie reviews displayed in the editor. Using this object we have retrieved the post ID and used that to query the database to get the associated Director’s name and Rating which in turn render the fields on the screen. When a new entry is added then the get_post_meta returns an empty string which results in displaying empty fields in the meta box.
Step 4: Registering a Save Post Function
add_action( 'save_post', 'add_movie_review_fields', 10, 2 );
This function is called when posts get saved in the database.
Step 5: Implementation of the add_movie_review_fields Function
function add_movie_review_fields( $movie_review_id, $movie_review ) {
// Check post type for movie reviews
if ( $movie_review->post_type == 'movie_reviews' ) {
// Store data in post meta table if present in post data
if ( isset( $_POST['movie_review_director_name'] ) && $_POST['movie_review_director_name'] != '' ) {
update_post_meta( $movie_review_id, 'movie_director', $_POST['movie_review_director_name'] );
if ( isset( $_POST['movie_review_rating'] ) && $_POST['movie_review_rating'] != '' ) {
update_post_meta( $movie_review_id, 'movie_rating', $_POST['movie_review_rating'] );
This function is executed when posts are saved or deleted from the admin panel. Here after checking for the type of received post data, if it is a Custom Post Type then it checks again to see if the meta box elements have been assigned values and then finally stores the values in those fields.
Step 6: Disabling the Default Custom Fields OptionWhile creating the custom post type we have defined a function create_movie_review. Remove the custom-fields element from the supports array because this is no longer required. Now if you save the file and open the Movie Reviews editor, you will notice two fields in the meta box named Movie Author and Movie Rating. Similarly you can add other elements too.
Creating a Custom Template Dedicated to Custom Post TypesThe proper way to display custom post type data is by using custom templates for each of the custom post types. Here … [more]
Plugins  Custom_Post_Types  Meta_Boxes  plugin_development  from google
october 2012 by Lorikb

related tags

admin  boilerplate  buttons  church  coding  custom_post_types  customization  databases  favorites  forms  framework  free  general  gist  github  gpl  how_to  inspiration  meta_boxes  monetization  mvc  oop  php  plugin  plugins  premium  repository  resource  skeleton  slideshow  smashing-magazine  snippet  theme_development  tips  tools  tutorial  tutorials  wordpress  wordpress_3.5  wordpress_plugin 

Copy this bookmark: