WordPress – Add Retina Image Support to Your Theme

Today, with increasing of high resolution devices, Client ask developer to add retina image support to their theme. Support Retina is to display high quality image on high resolution devices. This means we need to create high resolution images and to load right images based on screen resolutions.

There are some plugins available on WordPress for regular users to add retina display images. Searching a wordpress directory for plugin shows below 5 plugins on top

Each plugin show use different way to show retina images but internal all  includes two things, A detection script and a retina-ready image creation function. For developer who want to include the feature of displaying retina image to their theme, It very first step to select right JavaScript to detect the screen resolution and display the image.

Detect Screen Display

We need to display high quality image if user device is supporting it. The best way to detect a screen is using JavaScript.  I generally use a script called retina.js by Imulus. Its size is only 4kb and includes all the front-end functionality you need to detect a retina display and load the right image.

Copy retina.js file to your theme /js folder. It should be in right place to enqueue the script correctly.

Add following code to your functions.php file

add_action( 'wp_enqueue_scripts', 'retina_support_enqueue_scripts' );
/**
 * Enqueueing retina.js
 *
 * This function is attached to the 'wp_enqueue_scripts' action hook.
 */
function retina_support_enqueue_scripts() {
    wp_enqueue_script( 'retina_js', get_template_directory_uri() . '/js/retina.js', '', '', true );
}

Above code is enough to detect the screen display. Now we have to create function to create high quality image.

High Quality Image Creation

We need to add a function such that each time image is uploaded or added a high resolution image is created automatically and stored with @2x added to the filename. The detection JavaScript will search for @2x suffix in filename to load the retina-ready version of the image if required.

In order to make sure that a retina-ready image is created automatically whenever an image is uploaded, you need to hook into the appropriate WordPress filter. The correct one to use is wp_generate_attachment_metadata.

Add the following code in functions.php of your theme

add_filter( 'wp_generate_attachment_metadata', 'retina_support_attachment_meta', 10, 2 );
/**
 * Retina images
 *
 * This function is attached to the 'wp_generate_attachment_metadata' filter hook.
 */
function retina_support_attachment_meta( $metadata, $attachment_id ) {
    foreach ( $metadata as $key => $value ) {
        if ( is_array( $value ) ) {
            foreach ( $value as $image => $attr ) {
                if ( is_array( $attr ) )
                    retina_support_create_images( get_attached_file( $attachment_id ), $attr['width'], $attr['height'], true );
            }
        }
    }

    return $metadata;
}

The above function checks to see if the uploaded file is an image. If it is, then it processes it using the retina_support_create_images() function.

Create An Image

Now as we checked if image is added and its time to create high quality image.

This code will also be placed in functions.php

/**
 * Create retina-ready images
 *
 * Referenced via retina_support_attachment_meta().
 */
function retina_support_create_images( $file, $width, $height, $crop = false ) {
    if ( $width || $height ) {
        $resized_file = wp_get_image_editor( $file );
        if ( ! is_wp_error( $resized_file ) ) {
            $filename = $resized_file->generate_filename( $width . 'x' . $height . '@2x' );

            $resized_file->resize( $width * 2, $height * 2, $crop );
            $resized_file->save( $filename );

            $info = $resized_file->get_size();

            return array(
                'file' => wp_basename( $filename ),
                'width' => $info['width'],
                'height' => $info['height'],
            );
        }
    }
    return false;
}

By this function, new retina image will be created  with suffix @2x added to the name. Now detection script will work with these new image.

That’s all you need to do to make it work, but adding one extra function will help in reducing the usage of server bytes. This function is for deleting the image that we have created for retina display when original image is deleted.

Delete the Image

If is a good to delete the retina-image if original image is deleted.

Add following code to functions.php of your theme

add_filter( 'delete_attachment', 'delete_retina_support_images' );
/**
 * Delete retina-ready images
 *
 * This function is attached to the 'delete_attachment' filter hook.
 */
function delete_retina_support_images( $attachment_id ) {
    $meta = wp_get_attachment_metadata( $attachment_id );
    $upload_dir = wp_upload_dir();
    $path = pathinfo( $meta['file'] );
    foreach ( $meta as $key => $value ) {
        if ( 'sizes' === $key ) {
            foreach ( $value as $sizes => $size ) {
                $original_filename = $upload_dir['basedir'] . '/' . $path['dirname'] . '/' . $size['file'];
                $retina_filename = substr_replace( $original_filename, '@2x.', strrpos( $original_filename, '.' ), strlen( '.' ) );
                if ( file_exists( $retina_filename ) )
                    unlink( $retina_filename );
            }
        }
    }
}

In this tutorial we learn how to add support of displaying retina image in WordPress theme. This will help theme developer in adding retina support to their theme.

 

Thanks to wptuts+.

WordPress Essential Plugins – Every Website Required

Plugins are tools to extend the functionality of WordPressWordPress Plugins allow easy modification, customization, and enhancement to a WordPress blog. Instead of changing the core programming of WordPress, you can add functionality with WordPress Plugins.

What is WordPress Plugins?

Here is a basic definition: A WordPress Plugin is a program, or a set of one or more functions, written in the PHP scripting language, that adds a specific set of features or services to the WordPress weblog, which can be seamlessly integrated with the weblog using access points and methods provided by the WordPress Plugin Application Program Interface (API).

SEO Related WordPress Essential Plugins

SEO is something which every site requires to make their business increase. SEO is a technique which helps search engines find and rank your site higher than the millions of other sites in response to a search query. SEO thus helps you get traffic from search engines.

WordPress SEO by Yoast

Improve your WordPress SEO: Write better content and have a fully optimized WordPress site using the WordPress SEO plugin by Yoast. WordPress SEO is the most complete and advanced WordPress SEO plugin that exists today. It incorporates everything from a snippet preview and page analysis functionality that helps you optimize your pages content, images titles, meta descriptions and more to XML sitemaps. This plugin helps you to optimize your page content, image titles, meta descriptions, comes with tons of other features like Robots Meta configuration, breadcrumbs, permalink cleanup, canonical link element support, and optimized post titles.

 All in One SEO Pack

All in one SEO WordPress PluginWordPress SEO plugin to automatically optimize your WordPress blog for Search Engines. Another free WordPress seo plugins which can be used to Optimizes your WordPress blog for Search Engines (Search Engine Optimization).

Comes with features to support google analytics,custom post types, Advanced Canonical URLs, Built-in API so other plugins/themes can access and extend functionality.

Google XML Sitemaps

This plugin will generate a special XML sitemap which will help search engines to better index your blog. Google XML Sitemaps plugin generates XML sitemaps for your WordPress website, so that it becomes easy for search engine crawlers like Google and Bing, to index your site better. It notifies all the major search engines when you create new content, helping your site be more thoroughly indexed.

SEO Friendly Images

SEO Friendly Images automatically adds alt and title attributes to all your images improving traffic from search engines. SEO friendly Images automatically adds alt and title attributes to your images. If your images inside post or page content don’t have alt or title attribute then this plugins adds them according to your plugins settings so images inside your content becomes seo optimized.

Broken Link Checker

This plugin will check your posts, comments and other content for broken links and missing images, and notify you if any are found. This plugin is very helpful to find all the broken links on your website. This plugin Monitors links in your posts, pages, comments, the blogroll, and custom fields (optional). Detects links that don’t work, missing images and redirects. Notifies you either via the Dashboard or by email.

WordPress Essential Any-Spam and Security Plugins

Every Website require to stop spamming. Stopping bot generated comments. Many Plugins are available to stop span. Here I have listed some good plugin available in WordPress.

Akismet

akismetAkismet filters out your comment and track-back spam for you, so you can focus on more important things. Akismet is the best wordpress anti spam plugin to protect your website from web spam. Akismet plugin filters comments and trackback spam. It runs on autopilot and provides 24-hour protection. Akismet is the best automated spam killer that actually gets better as it learns.

SI CAPTCHA Anti-Spam

SI CAPTCHA Anti-SpamAdds CAPTCHA anti-spam methods to WordPress on the forms for comments, registration, lost password, login, or all. For WP, WPMU, and BuddyPress. SI CAPTCHA Anti-Spam plugin prevents spam from automated bots by adding a CAPTCHA in comment, registration, login and lost password forms. So your websites comment,login and registration forms becomes more secure from spams.

WP-reCAPTCHA

WP-reCAPTCHAIntegrates reCAPTCHA anti-spam methods with WordPress including comment, registration, and email spam protection. reCAPTCHA is popular and widely accepted CAPTCHA systems on many websites. WP-reCaptcha plugin integrates reCAPTCHA anti-spam methods in WordPress as comment, registration forms and email protection.

Login LockDown

Login LockDown records the IP address and timestamp of every failed login attempt. If more than a certain number of attempts are detected within a short period of time from the same IP range, then the login function is disabled for all requests from that range. This helps to prevent brute force password discovery.

Better WP Security

Better WP Security

The easiest, most effective way to secure WordPress. Improve the security of any WordPress site in seconds. This plugin can Remove the meta “Generator” tag, Change the urls for WordPress dashboard including login, admin, and more, Completely turn off the ability to login for a given time period (away mode), Remove theme, plugin, and core update notifications from users who do not have permission to update them, Remove Windows Live Write header information, Remove RSD header information, Rename “admin” account, Change the ID on the user with ID 1, Change the WordPress database table prefix, Change wp-content path, Removes login error messages and Display a random version number to non administrative users anywhere version is used.

Essential Polls and Comments WordPress plugins

 

CommentLuv

Reward your readers by automatically placing a link to their last blog post at the end of their comment. Encourage a community and discover new posts. CommentLuv Pro has even more amazing features that can bring even more traffic and comments to your blog by giving you the ability to fight spam, add keywords, integrate twitterlink, add a top commentators widget, social enticements and by having it installed on your site, you get advanced backlink features on EVERY CommentLuv blog when you comment (there are 10’s of thousands of CommentLuv blogs).

Facebook Comments For WordPress

Allows your visitors to comment on posts using their Facebook profile. Supports custom styles, notifications, combined comment counts, recent comments. This plugin integrates the Facebook commenting system (new, old or both) right into your website. If a reader is logged into Facebook while viewing any comment-enabled page or post, they’ll be able to leave a comment using their Facebook profile.

Disqus Comment System

Disqus Comment SystemDisqus, pronounced “discuss”, is a service and tool for web comments and discussions. Disqus makes commenting easier and more interactive, while connecting websites and commenters across a thriving discussion community.  The Disqus for WordPress plugin seamlessly integrates using the Disqus API and by syncing with WordPress comments.

Subscribe To Comments

Subscribe to Comments allows commenters on an entry to subscribe to e-mail notifications for subsequent comments. The plugin includes a full-featured subscription manager that your commenters can use to unsubscribe to certain posts, block all notifications, or even change their notification e-mail address!

WP-Polls

Adds an AJAX poll system to your WordPress blog. You can also easily add a poll into your WordPress’s blog post/page. WP-Polls is extremely customizable via templates and css styles and there are tons of options for you to choose to ensure that WP-Polls runs the way you wanted. It now supports multiple selection of answers.

Essential Social WordPress Plugin

AddThis

AddthisAddThis Share Buttons help drive traffic to your site by helping visitors share, bookmark and email your content to over 330 services. Get more traffic back to your site by installing the AddThis WordPress plugin.With AddThis, your users can promote your content by sharing to over 330 of the most popular social networking and bookmarking sites (like Facebook, Twitter, Pinterest, Google+ and LinkedIn).

ShareThis: Share Buttons and Sharing Analytics

ShareThis Share Buttons and Sharing AnalyticsQuick & easy sharing service that allows your users to share content – features Open Graph Sharing, Hovering Bar and CopyNShare! Increase social activity on your site with the ShareThis and ShareNow widgets. With access to 120 social channels (including Facebook, Twitter, Like, +1, Email and more), The ShareThis widget is a quick and easy sharing solution for your site to keep your audience engaged in your content and increase traffic to your site. You can also customize your widget for seamless integration to your site. You have the option to use small or large buttons, add counters and place the widget in a clear location for your users to share.

Sociable

Sociable plugin adds a bar of icons of different social networking and bookmarking sites that you can choose for your articles. Using sociable plugin visitors of your website can easily share posts from your website on their social bookmarking accounts.

Essential Stats and Tracking Plugins

WassUp Real Time Analytics

WassUp Real Time AnalyticsAnalyze your visitors traffic with real-time statistics, a lot of chronological information, charts, a sidebar widget. WassUp is a WordPress plugin to track your visitors in real-time. It has a very readable and fancy admin console to keep track of your visitors that gives you a detailed view into almost everything your users are doing on your site. It is very useful for SEO or statistics maniacs.

WP-UserOnline

Enable you to display how many users are online on your WordPress blog with detailed statistics. This plugin enables you to display how many users are online on your WordPress site, with detailed statistics of where they are and who they are (Members/Guests/Search Bots).

Count per Day

Count per DayVisit Counter, shows reads and visitors per page, visitors today, yesterday, last week, last months and other statistics. This plugin count reads and visitors, shows reads per page, shows visitors today, yesterday, last week, last months and other statistics on dashboard, shows country of your visitors, you can show these statistics on frontend per widget or shortcodes too.

Jetpack by WordPress.com

Jetpack by WordPress.comJetpack is a WordPress plugin that supercharges your self-hosted WordPress site with the awesome cloud power of WordPress.com. This plugin can Simple, concise stats with no additional load on your server. Previously provided byWordPress.com StatsEmail subscriptions for your blog’s posts and your post’s comments, Social networking enabled comment system, Likes, allowing your readers to show their appreciation of your posts, Monitor and manage your site’s activity with, Notifications in your Toolbar and on WordPress.com, Simple, Akismet-backed contact forms.

Google Analytics for WordPress

Google Analytics for WordPressTrack your WordPress site easily and with lots of metadata: views per author & category, automatic tracking of outbound clicks and pageviews. Simple installation through integration with Google Analytics API: authenticate, select the site you want to track and you’re done. This plugin uses the asynchronous Google Analytics tracking code, the fastest and most reliable tracking code Google Analytics offers. This plugin have option to manually place the tracking code in another location.

Other Essential Plugin for WordPress

Contact Form 7

Contact Form 7Contact Form 7 can manage multiple contact forms, plus you can customize the form and the mail contents flexibly with simple markup. The form supports Ajax-powered submitting, CAPTCHA, Akismet spam filtering and so on.

 

WordPress PopUp

WordPress PopUp allows you to display a fancy popup (powered as a popover!) to visitors sitewide or per blog, a *very* effective way of advertising a mailing list, sp. Good plugin to add popup ads or banners inside popup on your website. Comes with option to restrict popup from any particular page or posts.

Nrelate

nrelateNrelate display related content in a cool flyout box. nrelate is not just another related posts plugin. Patent-pending technology continuously analyzes your website content and displays other related posts from your website. This ultimately leads to higher page-views for your site, and a better user experience for your visitors.

 

Setting Different Template/Design for Post per Category – WordPress

WordPress is providing various ways to set different template on category page but How about if I want to set different template for each category for Single Post Page.

Today I will show how can we achieve this with simple code in single.php

First We need to create single post template for various categories as follow

single_music.php
single_sms.php
single_news.php
single_default.php //For default single post template  for post other than above categories.

Above three files i create because i want to use different single post page template for my music, SMS, and news category respectively. You can create as much file as you can

You can simply create copy of your single.php file and rename it with new template and do the changes that you want for each category single page.

After that open your single.php file remove all code and add following code.

<?php
  $post = $wp_query->post;
  if (in_category('portfolio')) {
      include(TEMPLATEPATH.'/single_music.php');
  } elseif (in_category('news')) {
      include(TEMPLATEPATH.'/single_news.php');
  } elseif(in_category('wordpress')) {
      include(TEMPLATEPATH.'/single_sms.php');
  }
  else{
      include(TEMPLATEPATH.'/single_default.php');
  }
?>

Please comment here if this post is help to you or you have any queries.

 

WordPress How to set SESSION Custom Variable While Login

Hello friends,

Sometimes we need to set custom session variable for using in our custom code or any other web application which also running parallely with our wordpress installation. Also some time there is need to set and destroy our session variable for our custom web application when wordpress user login or logout.

So first of all we need to enable session in wordpress. I have tested this code in wordpress 3.X. First we need to start the session every time wordpress initialize. To initialize session in wordpress we can use below code.

add_action('init', 'session_manager'); 
function session_manager() {
	if (!session_id()) {
		session_start();
	}
}

This will start the session every time wordpress loads. In this function you can write any other session variable that you need to set default. Then we also need to destroy the session when wordpress user logout. To destroy the session and unset any variable we can use below code:

add_action('wp_logout', 'session_logout');
function session_logout() {
	session_destroy();
}

In this function you can write any other session variable that you want to unset.

Now, How can we set user data into the session variable? Answer is very simple see the below code:

add_filter('authenticate', 'check_login', 10, 3);
function check_login($user, $username, $password) {
     $user = get_user_by('login', $username);
     $_SESSION['userdata']=$user; return $user;
}

Here we add authentication filter of wordpress to set the session. Also we can use this authenticate filter to restrict certain user from login into the wordpress. This function will set the session and later we can use it any where in the wordpress. Also you can set other system session variable so that when any user logs in wordpress he also get logs in other Custom system but condition is both wordpress installation and custom system need to be on same server.

Please post your comment here if this information helps you. I will keep posting more as I come to know more things.

Thank you 🙂

 

 

 

WordPress Insert Post from Front End

Hi, In this article I will show one example plugin for making post entry from wordpress front end.

Screenshot:

Below is the sample code for the plugin

<?php
/*
Plugin Name: Insert Post Fontend Demo Plugin
Plugin URI: http://thedigilife.com
Description: Example Insert Post Plugin and Approval from admin
Author: The Digi Life
Version: 1.0
Author URI: http://thedigilife.com
*/
add_shortcode('insertpost','display_insert_form');
function display_insert_form($atts)
{
	if ( !empty($_POST) && !wp_verify_nonce($_POST['insert'],'insert_form') )
	{
		echo 'Sorry, Problem in submitting form';
	}
	else
	{
		// process form data
		$post_data = array(
		'post_title' => $_POST['title'],
		'post_content' => $_POST['description'],
		'post_status' => 'pending',
		'post_author' => 1,
		'post_category' => null
		);
		if($post_id = wp_insert_post($post_data)) echo "Data Succcessfully added";
	}
	?>
	<form action="" method="post" name="insert_form">
		<table>
			<tr>
				<td><label>Title</label></td>
				<td><input type="text" name="title" id="title"></td>
			</tr>
			<tr>
				<td><label>Description</label></td>
				<td><textarea rows="7" cols="10" name="description" id="description"></textarea></td>
			</tr>
			<tr>
				<td colspan="2"><input type="submit" id="button"></td>
			</tr>
			<?php wp_nonce_field('insert_form','insert'); ?>
		</table>
	</form>
	<?php
}

We can insert post in wordpress using wp_insert_post which is explained Here

In this sample I have created one sample shortcode for displaying plugin on front and in short code function I have added form to display and before that if post is submitted we will insert the post into database.

 Download | Source Code

 

WordPress Admin listing Table and Paging

Almost svery wordpress plugin developer needs to make Admin side listing for any custom table. This table generally store information that is gather from website and/or end users. Listing of table help to view the data in list format. It also allow admin to add, edit and Delete the data. It also allow bulk action for delete.

During my plugin development, I always wonder that how to make admin side listing for custom table which looks same as post and page listing. Also how can I make pagination for the table. I have searched for pagination and found many class to use that you can also found in my previous post. But I want to make it looks like as below:

 

 

After Searching for this I come to know that wordpress also providing the class for listing and paging for custom table. Class Name is Wp_List_Table. Wp_List_Table class is used to create admin screens for the wordpress. We need to extends this class and overload its method to use it.

Now the question is how to use this class and create admin side listing for our created custom table.

WordPress is providing one very good example plugin to see how we can create admin side listing for the custom table. You can find the example plugin Here

This example display code using Array of data. Instead of data we can use any database table. For creating your own table listing copy paste data into your file and follow below steps

Step 1: Create a new file under your plugin directory

Step 2: Include WP_List_Table class file into your file as follow:

if(!class_exists('WP_List_Table')){
 require_once( ABSPATH . 'wp-admin/includes/class-wp-list-table.php' );
}

Step 3: Create class for your custom table and extends it to WP_List_Table.

For this you can copy whole class from example plugin and paste it in your plugin file and rename the class name from TT_Example_List_Table to something else which is preferable for your plugin.

Step 4: If you are using database table for fetching data which will always a case in real life,  then delete the example data array.

We will fetch the data from database when it will be needed. Remove the below code:

var $example_data = array(
	 array(
	 'ID' => 1,
	 'title' => '300',
	 'rating' => 'R',
	 'director' => 'Zach Snyder'
	 ),
	 array(
	 'ID' => 2,
	 'title' => 'Eyes Wide Shut',
	 'rating' => 'R',
	 'director' => 'Stanley Kubrick'
	 ),
	 array(
	 'ID' => 3,
	 'title' => 'Moulin Rouge!',
	 'rating' => 'PG-13',
	 'director' => 'Baz Luhrman'
	 ),
	 array(
	 'ID' => 4,
	 'title' => 'Snow White',
	 'rating' => 'G',
	 'director' => 'Walt Disney'
	 ),
	 array(
	 'ID' => 5,
	 'title' => 'Super 8',
	 'rating' => 'PG-13',
	 'director' => 'JJ Abrams'
	 ),
	 array(
	 'ID' => 6,
	 'title' => 'The Fountain',
	 'rating' => 'PG-13',
	 'director' => 'Darren Aronofsky'
	 ),
	 array(
	 'ID' => 7,
	 'title' => 'Watchmen',
	 'rating' => 'R',
	 'director' => 'Zach Snyder'
	 )
	 );

Step 5: Setting up the naming and some configs for table listing.

function __construct(){
 global $status, $page;

 //Set parent defaults
 parent::__construct( array(
 'singular' => 'movie', //singular name of the listed records
 'plural' => 'movies', //plural name of the listed records
 'ajax' => false //does this table support ajax?
 ) );

 }

Step 6: Set Default common value display for the every column using.

function column_default($item, $column_name){
 switch($column_name){
 case 'rating':
 case 'director':
 return $item[$column_name];
 default:
 return print_r($item,true); //Show the whole array for troubleshooting purposes
 }
 }

This method is called when the parent class can’t find a method  specifically build for a given column. Generally, it’s recommended to include one method for each column you want to render, keeping your package class neat and organized. For example, if the class needs to process a column named ‘title’, it would first see if a method named $this->column_title() exists – if it does, that method will be used. If it doesn’t, this one will be used. Generally, you should try to use custom column methods as much as  possible.

Step 7: If you have any column column which need to be display diffidently from other in the view. We can create this by below syntax

function column_<field name>($item){
//Some Code
return "formated text";
}

In example below is given

function column_title($item){

 //Build row actions
 $actions = array(
 'edit' => sprintf('<a href="?page=%s&action=%s&movie=%s">Edit</a>',$_REQUEST['page'],'edit',$item['ID']),
 'delete' => sprintf('<a href="?page=%s&action=%s&movie=%s">Delete</a>',$_REQUEST['page'],'delete',$item['ID']),
 );

 //Return the title contents
 return sprintf('%1$s <span style="color:silver">(id:%2$s)</span>%3$s',
 /*$1%s*/ $item['title'],
 /*$2%s*/ $item['ID'],
 /*$3%s*/ $this->row_actions($actions)
 );
 }

step 8: Display Check boxes for the bulk action.

&nbsp;function column_cb($item){
  return sprintf(
'<input type="checkbox" name="%1$s[]" value="%2$s" />',
/*$1%s*/ $this->_args['singular'], //Let's simply repurpose the table's singular label ("movie")
/*$2%s*/ $item['ID'] //The value of the checkbox should be the record's id
  );
}

step 9: get all column. here we specify which column to get for display.

This method dictates the table’s columns and titles. This should return an array where the key is the column slug (and class) and the value  is the column’s title text. If you need a checkbox for bulk actions, refer to the $columns array below.

function get_columns(){
 $columns = array(
 'cb' => '<input type="checkbox" />', //Render a checkbox instead of text
 'title' => 'Title',
 'rating' => 'Rating',
 'director' => 'Director'
 );
 return $columns;
 }

Step 10: Decide which column to make sortable. This Method is optional.

If you want one or more columns to be sortable (ASC/DESC toggle), you will need to register it here. This should return an array where the key is the column that needs to be sortable, and the value is db column to sort by. Often, the key and value will be the same, but this is not always the case (as the value is a column name from the database, not the list table).
This method merely defines which columns should be sortable and makes them clickable – it does not handle the actual sorting. You still need to detect the ORDERBY and ORDER query string variables within prepare_items() and sort your data accordingly (usually by modifying your query).

function get_sortable_columns() {
 $sortable_columns = array(
 'title' => array('title',true), //true means its already sorted
 'rating' => array('rating',false),
 'director' => array('director',false)
 );
 return $sortable_columns;
 }

Step 11: Set up bulk action for selected check boxes. This method is optional

If you need to include bulk actions in your list table, this is the place to define them. Bulk actions are an associative array in the format ‘slug’=>’Visible Title’

If this method returns an empty value, no bulk action will be rendered. If you specify any bulk actions, the bulk actions box will be rendered with the table automatically on display().

Also note that list tables are not automatically wrapped in <form> elements, so you will need to create those manually in order for bulk actions to function.

function get_bulk_actions() {
 $actions = array(
 'delete' => 'Delete'
 );
 return $actions;
 }

Now we also need to set up what to do when any one of the bulk action has been called. This can done using below method. This method is optional.

function process_bulk_action() {
 //Detect when a bulk action is being triggered...
 if( 'delete'===$this->current_action() ) {
 wp_die('Items deleted (or they would be if we had items to delete)!');
 }
 }

step 12: This is most important step for the listing the table and fetching the database values.

Here find and delete the code

$data = $this->example_data;

Below that there is function

function usort_reorder($a,$b){
 $orderby = (!empty($_REQUEST['orderby'])) ? $_REQUEST['orderby'] : 'title'; //If no sort, default to title
 $order = (!empty($_REQUEST['order'])) ? $_REQUEST['order'] : 'asc'; //If no order, default to asc
 $result = strcmp($a[$orderby], $b[$orderby]); //Determine sort order
 return ($order==='asc') ? $result : -$result; //Send final sort direction to usort
 }
 usort($data, 'usort_reorder');

Also delete this code this code is now no more needed as we are sorting through database query. Add The below Code here

global $wpdb;
 $orderby = (!empty($_REQUEST['orderby'])) ? $_REQUEST['orderby'] : 'sent_time'; //If no sort, default to title
 $order = (!empty($_REQUEST['order'])) ? $_REQUEST['order'] : 'asc'; //If no order, default to asc
 $query='select * from <Table_name> order by '. $orderby . ' ' .$order;
 $data = $wpdb->get_results($query, 'ARRAY_A');

Here first we have called global variable which is available in wordpress for the database operation. ‘$wpdb’ . Then set order by and order values and get the data.

Every things else remain as it is in this function no need to change.

step 13: Now we need to create function which will be called when page is going to display. We just need to create object of our newly created class.

//Create an instance of our package class...
 $testListTable = new TT_Example_List_Table();
 //Fetch, prepare, sort, and filter our data...
 $testListTable->prepare_items();

And Display the data

<!-- Forms are NOT created automatically, so you need to wrap the table in one to use features like bulk actions -->
 <form id="movies-filter" method="get">
 <!-- For plugins, we also need to ensure that the form posts back to our current page -->
 <input type="hidden" name="page" value="<?php echo $_REQUEST['page'] ?>" />
 <!-- Now we can render the completed list table -->
 <?php $testListTable->display() ?>
 </form>

Conclusion

This will create both listing and pagination for custom table in wordpress. I think this is really easy to use it rather creating table by self and searching for the pagination class and adding them to the code.

This helps developers to create very neat and clean code. Also, This code is fully compatible with wordpress.

Please comment your queries, Suggestion, Like or Dislike post here.

Enjoy..!!!

Note: This example which I have used which is already available in wordpress listing table plugin. I have explained using database connection which was missing in the plugin. Hope this will helps every wordpress developers.

Thank you….

Add Pagination Into WordPress Admin For Plugin

Often in many application, such as in WordPress Plugin, we will need to deal with list of records. As the records grow, more records will need to be displayed. There is a catch though, if you retrieve all the records at one go because it will slow the system down.

In order to have a better user experience for record listing, paging comes into play. It’ll not only help to organize the records by limiting the number of records you want to show per page, it also cuts the down the time of retrieving records. Therefore, pagination plays a very important part in providing a great user experience when interacting with the data.

Imaging if you have a list of 1000 or more records that you want to display. Without pagination, listing all the records will definitely take quite awhile and also increase the load for the database server when executing the query. This is not very efficient, even though retrieving records from database can be cheap.

Now let’s say we want to add in pagination into the 1000 records, by specifying the limit, it will only shows the exact amount of records you want to view. This is a huge benefit for the database server load, because we are not retrieving all the records at once.

Below examples are 2 different type of pagination and a demo on how to add pagination into WordPress Plugin.

Simple PHP Pagination Class

Copy the following code and save as pager.php, this file will be the pagination class. With this pagination classfrom Happycodings, it’d help us add pagination to the list of records easily.

<?php
function findStart($limit) {
	if ((!isset($_GET['page'])) || ($_GET['page'] == "1")) {
		$start = 0;
		$_GET['page'] = 1;
	} else {
		$start = ($_GET['page']-1) * $limit;
	}
	return $start;
}

/*
 * int findPages (int count, int limit)
 * Returns the number of pages needed based on a count and a limit
 */
function findPages($count, $limit) {
	$pages = (($count % $limit) == 0) ? $count / $limit : floor($count / $limit) + 1; 
	return $pages;
} 

/*
* string pageList (int curpage, int pages)
* Returns a list of pages in the format of "« < [pages] > »"
**/
function pageList($curpage, $pages)
{
	$page_list = ""; 

	/* Print the first and previous page links if necessary */
	if (($curpage != 1) && ($curpage)) {
		$page_list .= ' <a href=" '.$_SERVER['PHP_SELF'].'?page=1" title="First Page">«</a> ';
	} 

	if (($curpage-1) > 0) {
		$page_list .= '<a href=" '.$_SERVER['PHP_SELF']."?page=".($curpage-1).'" title="Previous Page">&lt;</a> ';
	} 

	/* Print the numeric page list; make the current page unlinked and bold */
	for ($i=1; $i<=$pages; $i++) {
		if ($i == $curpage) {
			$page_list .= "<b>".$i."</b>";
		} else {
			$page_list .= '<a href=" '.$_SERVER['PHP_SELF'].'?page='.$i.'" title="Page'.$i.'">'.$i.'</a>';
		}
		$page_list .= " ";
	} 

	/* Print the Next and Last page links if necessary */
	if (($curpage+1) <= $pages) {
		$page_list .= '<a href="'.$_SERVER['PHP_SELF']."?page=".($curpage+1).'" title="Next Page">></a> ';
	} 

	if (($curpage != $pages) && ($pages != 0)) {
		$page_list .= '<a href="'.$_SERVER['PHP_SELF']."?page=".$pages.'" title="Last Page">»</a> ';
	}
	$page_list .= "</td>\n"; 
	return $page_list;
}

/*
* string nextPrev (int curpage, int pages)
* Returns "Previous | Next" string for individual pagination (it's a word!)
*/
function nextPrev($curpage, $pages) {
	$next_prev = ""; 

	if (($curpage-1) <= 0) {
		$next_prev .= "Previous";
	} else {
		$next_prev .= '<a href="'.$_SERVER['PHP_SELF']."?page=".($curpage-1).'">Previous</a>';
	} 

	$next_prev .= " | "; 

	if (($curpage+1) > $pages) {
		$next_prev .= "Next";
	} else {
		$next_prev .= '<a href="'.$_SERVER['PHP_SELF']."?page=".($curpage+1).'">Next</a>';
	}
	return $next_prev;
}
?>

Once you have the pager.php, instantiate the class as below. Change the $limit to your desired number of records to show per page and finally get the page list by echoing it out.

/* Instantiate class */
require_once("pager.php");
$p = new Pager; 

/* Show many results per page? */
$limit = 100; 

/* Find the start depending on $_GET['page'] (declared if it's null) */
$start = $p->findStart($limit); 

/* Find the number of rows returned from a query; Note: Do NOT use a LIMIT clause in this query */
$count = mysql_num_rows(mysql_query("SELECT field FROM table")); 

/* Find the number of pages based on $count and $limit */
$pages = $p->findPages($count, $limit); 

/* Now we use the LIMIT clause to grab a range of rows */
$result = mysql_query("SELECT * FROM table LIMIT ".$start.", ".$limit); 

/* Now get the page list and echo it */
$pagelist = $p->pageList($_GET['page'], $pages);
echo $pagelist; 

/* Or you can use a simple "Previous | Next" listing if you don't want the numeric page listing */
//$next_prev = $p->nextPrev($_GET['page'], $pages);
//echo $next_prev;
/* From here you can do whatever you want with the data from the $result link. */

Digg Style Pagination

As the above simple pagination class is enough for us to display a list of page numbering for the records, but what will happen if there are a few hundreds of pages, isn’t the row of page numbering going to be very long too?

Here is another nice Digg Style Pagination class that you can consider if you think there will be a lot of pages for your records.

Download the pagination.class.php.

Go through the guide to customize the style or desired output for the paging you want. Now, to give you a clearer view on how to add this Digg Style Pagination class. Check out below to find out how to add the Digg Style Pagination to a WordPress Plugin.

How To Add Pagination To WordPress Plugin?

If you are building a WordPress plugin that require to display a list of records from database. As records get huge, you will need to have pagination so that you can organize your records well.

First, you will need to download the pagination.class.php and save it in your WordPress Plugin folder.

Next, in the PHP file that you want to list your records, insert the following code. Below are some of the methods we used from the pagination class. For the full list of methods, please refer to Digg Style Pagination Class Help Page.

Note that you will need to change the SQL query, pagination class configuration and table fields, in order to work nicely with your WordPress Plugin.

<?php

$items = mysql_num_rows(mysql_query("SELECT * FROM wp_table;")); // number of total rows in the database

if($items > 0) {
	$p = new pagination;
	$p->items($items);
	$p->limit(30); // Limit entries per page
	$p->target("admin.php?page=list_record");
	$p->currentPage($_GET[$p->paging]); // Gets and validates the current page
	$p->calculate(); // Calculates what to show
	$p->parameterName('paging');
	$p->adjacents(1); //No. of page away from the current page

	if(!isset($_GET['paging'])) {
		$p->page = 1;
	} else {
		$p->page = $_GET['paging'];
	}

	//Query for limit paging
	$limit = "LIMIT " . ($p->page - 1) * $p->limit . ", " . $p->limit;

} else {
	echo "No Record Found";
}

?>

<!-- Now we'll display the list of records -->

<div class="wrap">
	<h2>List of Records</h2>

	<div class="tablenav">
		<div class='tablenav-pages'>
			<?php echo $p->show(); // Echo out the list of paging. ?>
		</div>
	</div>

	<table class="widefat">
		<thead>
			 <tr>
				 <th>ID</th>
				 <th>Full Name</th>
				 <th>Email</th>
			 </tr>
		</thead>
		<tbody>
		<?php
		$sql = "SELECT * FROM $wp_table ORDER BY id DESC $limit";
		$result = mysql_query($sql) or die ('Error, query failed');

		if (mysql_num_rows($result) > 0 ) {
			while ($row = mysql_fetch_assoc($result)) {
			$id = $row['id'];
			$fullname = $row['fullname'];
			$email = $row['email'];
			?>
			<tr>
				<td><?php echo $id; ?></td>
				<td><?php echo $fullname; ?></td>
				<td><?php echo $email; ?></td>
			</tr>
			<?php 
			}
		} else { ?>
			<tr>
				<td>No Record Found!</td>
			<tr>
		<?php } ?>
		</tbody>
	</table>
</div>

Now you know How to Add a Digg Style Pagination to a WordPress Plugin, it should make your listing of data much more efficient. Pagination saves your time and bandwidth so you can concentrate more on other implementing issues.

Still not sure about this tutorial on adding pagination? Or simply have an idea to share? Feel free to contact us or leave a comment here!

 

 


Adding New Fields to the attachment of wordpress

Recently I was developing plugin for image features. I have to add some fields to the attachment window of wordpress or I can say in Add media box.

We can achieve this by using two hooks of wordpress.
“attachment_fields_to_edit” and “attachment_fields_to_save”;

attachment_fields_to_edit

function get_attachment_fields_to_edit($post,$errors=null){
 // Some Code
 $form_fields = apply_filters("attachment_fields_to_edit", $form_fields, $post);
 // Some Code
 }
  • $form_fields is a special array which will be described in detail in a moment.
  • $post is the attachment as an object (attachments are treated as post objects in WordPress).

attachment_fields_to_save

functionmedia_upload_form_handler(){
	//Some Code
	$post=apply_filters("attachment_fields_to_save",$post,$attachment);
	//Some Code
}
  • $post is the attachment as an array (attachments are treated as post objects in WordPress).
  • $attachment is the attachment part of the form $_POST which will include the fields setup through the attachment_fields_to_edit hook.

Note: Be careful in your code, as $post is sent to one function as an object and to the other as an array.

We will add this fields information to Custom Fields.

How to add this Fields to Custom Fields for Working is Properly

The new fields being added will be saved as post meta, just like the custom fields section of the post/page edit screen. Fields prefixed with an underscore (_my_custom_field) will not be listed in the drop down of available custom fields on the post/page screen; all other existing post meta fields will be listed. We can use this knowledge to hide the fields we’re adding to the media form, since they aren’t relevant for posts/pages.

There is a similar rule to keep in mind when choosing the $form_fields array key to use for your new field. Here, if you use an underscore ($form_fields[‘_my_custom_field’]) your field will be skipped and will not be added to the form.

So in order to show our fields in the media form, but also not list them in the page/post custom fields drop down, we must combine both methods. This will invlove both the edit and save functions we’ll be creating. For the ‘attachment_fields_to_edit‘ hook we’ll set the $form_fields keys up to not have underscore prefixes, and for the ‘attachment_fields_to_save‘ hook we’ll prefix our fields with an underscore before saving them as post meta. This is a workaround worth doing in order to not muddy our users’ interface with unneeded info.

Hook 1: attachment_fields_to_edit

<?php
/**
 * Adding our custom fields to the $form_fields array
 *
 * @param array $form_fields
 * @param object $post
 * @return array
 */
function my_image_attachment_fields_to_edit($form_fields, $post) {
	// $form_fields is a special array of fields to include in the attachment form
	// $post is the attachment record in the database
	// $post->post_type == 'attachment'
	// (attachments are treated as posts in WordPress)
	// add our custom field to the $form_fields array
	// input type="text" name/id="attachments[$attachment->ID][custom1]"
	$form_fields["custom1"] = array(
	"label" => __("Custom Text Field"),
	"input" => "text", // this is default if "input" is omitted
	"value" => get_post_meta($post->ID, "_custom1", true)
	);
	// if you will be adding error messages for your field,
	// then in order to not overwrite them, as they are pre-attached
	// to this array, you would need to set the field up like this:
	$form_fields["custom1"]["label"] = __("Custom Text Field");
	$form_fields["custom1"]["input"] = "text";
	$form_fields["custom1"]["value"] = get_post_meta($post->ID, "_custom1", true);
	return $form_fields;
}
// attach our function to the correct hook
add_filter("attachment_fields_to_edit", "my_image_attachment_fields_to_edit", null, 2);

The $form_fields array has several options for including different types of inputs and custom content. I’ve compiled the various methods below with notes and screenshots of how they render in the form.

Text Input

// input type="text"
$form_fields["custom1"]["label"] = __("Custom Text Field");
$form_fields["custom1"]["input"] = "text"; // this is default if "input" is omitted
$form_fields["custom1"]["value"] = get_post_meta($post->ID, "_custom1", true);

Hook 2: attachment_fields_to_save

Saving your custom fields is a much simpler process than adding them to the form; just check if your field is set and update its value as post meta. Remeber to prefix your field with an underscore when saving to hide it on the post/page edit screen.

/**
 * @param array $post
 * @param array $attachment
 * @return array
 */
function my_image_attachment_fields_to_save($post, $attachment) {
 // $attachment part of the form $_POST ($_POST[attachments][postID])
 // $post attachments wp post array - will be saved after returned
 // $post['post_type'] == 'attachment'
 if( isset($attachment['my_field']) ){
 // update_post_meta(postID, meta_key, meta_value);
 update_post_meta($post['ID'], '_my_field', $attachment['my_field']);
 }
 return $post;
}

You can also add errors here that will automatically be displayed below your field in the form. The$post['errors'] array gets merged with the $form_fields array before being sent through theattachment_fields_to_edit hook.

/**
 * @param array $post
 * @param array $attachment
 * @return array
 */
function my_image_attachment_fields_to_save($post, $attachment) {
 if( isset($attachment['my_field']) ){
 if( trim($attachment['my_field']) == '' ){
 // adding our custom error
 $post['errors']['my_field']['errors'][] = __('Error text here.');
 }else{
 update_post_meta($post['ID'], 'my_field', $attachment['my_field']);
 }
 }
 return $post;
}

Thanks to http://net.tutsplus.com

I have posted here for my future reference.