You should be familiar with custom fields in WordPress. We use them on a post or a page to add extra data. In WordPress attachments are also saved as posts, so custom fields are available for them too.
Today we’ll see how we can add some custom fields so that attachments can carry more information than just the default data.
/>
What We’ll Do
First of all, we are going to create a plugin to handle the attachments custom fields. It will get a set of options, bake them so they become part of the form when we edit an attachment, and save them into the database.
I will pass quickly on this part as it’s not the main purpose of this tutorial.
Create a new folder in the plugins directory (wp-content/plugins/media-fields/ for example) and put a file (named plugin.php) inside. Let’s also put a file called custom_media_fields.php which will hold our options.
This is what your plugin.php file should look like at first:
/*
Plugin Name: Wptuts+ Custom Media Fields
Plugin URI:
Description: Create attachments custom fields
Version: 0.1
Author: Guillaume Voisin
Author URI: http://wp.tutsplus.com/author/guillaumevoisin
License: GPL2
*/
require_once( plugin_dir_path( __FILE__ ) . '/custom_media_fields.php' );
Class Wptuts_Custom_Media_Fields
private $media_fields = array();
function __construct( $fields )
public function applyFilter( $form_fields, $post = null )
function saveFields( $post, $attachment )
}
$cmf = new Wptuts_Custom_Media_Fields( $attchments_options );
This is the base we’ll populate in the following sections. For now, let’s define our set of options.
/>
2. Define Our Options
In the other file, let’s add some options to enhance the attachment edit form. We’ll consider, for this tutorial, options to improve images. For instance, we’ll add copyright, author description, watermark, rating, and image disposition fields.
It is basically an associative array which contains these parameters:
label – the field name that will be displayed
input – the input type (e.g text, select, radio, …)
helps – information to help the user filling in the field
application – which attchment mime type to apply
exclusions – which attchment mime type to exclude
required – is the field required? (default false)
error_text – optional field to describe the error (if required is set to true)
options – optional field for radio and select types
show_in_modal – whether to show the field in modal or not (default true)
show_in_edit – whether to show the field in classic edit view or not (default true)
extra_rows – additional rows to display content (within the same “tr” tag)
tr – additional rows (“tr” tag)
The highlitghted options represent options we will manually deal with whereas others are default ones WordPress will process automatically.
As we are dealing with images, we set the application parameter to “image“. It will actually apply to all kinds of images whose mime type starts with “image” such as image/jpeg, image/png and so on. You could exlude the gif mime type by setting it in the exclusions field for example.
Now our options are set, let’s dig into the hooks.
/>
3. The Hooks
As mentionned earlier, we’ll deal with two hooks.
We bind our two functions to those hooks in the constructor method.
$form_fields – An array of fields contained in the attachment edit form
$post – Object which represents the attachment itself
We will use the $form_fields parameter to merge our own fields and check each one of them against attachment requirements (mime type for instance).
public function applyFilter( $form_fields, $post = null )
// If our fields array is not empty
if ( ! empty( $this->media_fields ) )
// We browse our set of options
foreach ( $this->media_fields as $field => $values )
// If the field matches the current attachment mime type
// and is not one of the exclusions
if ( preg_match( "/" . $values['application'] . "/", $post->post_mime_type) && ! in_array( $post->post_mime_type, $values['exclusions'] ) )
// We get the already saved field meta value
$meta = get_post_meta( $post->ID, '_' . $field, true );
// Define the input type to 'text' by default
$values['input'] = 'text';
// And set it to the field before building it
$values['value'] = $meta;
// We add our field into the $form_fields array
$form_fields[$field] = $values;
}
}
// We return the completed $form_fields array
return $form_fields;
}
At this step, you should have your attachment edit form enhanced with the new fields we’ve added. But they will look like text inputs. We now have to consider different kinds of inputs (radio, checkbox, etc…).
So let’s edit our function to handle this. Replace the $values['input'] = 'text'; with the following code:
switch ( $values['input'] )
default:
case 'text':
$values['input'] = 'text';
break;
case 'textarea':
$values['input'] = 'textarea';
break;
case 'select':
// Select type doesn't exist, so we will create the html manually
// For this, we have to set the input type to 'html'
$values['input'] = 'html';
// Create the select element with the right name (matches the one that wordpress creates for custom fields)
$html = '';
// Set the html content
$values['html'] = $html;
break;
case 'checkbox':
// Checkbox type doesn't exist either
$values['input'] = 'html';
// Set the checkbox checked or not
if ( $meta == 'on' )
$checked = ' checked="checked"';
else
$checked = '';
$html = '';
$values['html'] = $html;
break;
case 'radio':
// radio type doesn't exist either
$values['input'] = 'html';
$html = '';
if ( ! empty( $values['options'] ) )
$i = 0;
foreach ( $values['options'] as $k => $v )
if ( $meta == $k )
$checked = ' checked="checked"';
else
$checked = '';
$html .= ' ';
$i++;
}
$values['html'] = $html;
break;
}
Now, we can build common HTML elements. Let’s check out our attachment edit form. It should look just like this:
/> Attachment edit form with custom fields
The custom fields, depending on whether you set their modal options to true or not, will also appear in the media modal form when you edit a post.
Custom fields in modal
Now our fields are displayed in our attachment edit form, we have to save them in the database. For this, we are going to use the second hook.
attachment_fields_to_save
This hook also has two parameters:
$post – array which represents the attachment entity
$attachment – contains all fields attached to the attachment post
Now, let’s fill the function saveFields we left in the previous section.
function saveFields( $post, $attachment )
// If our fields array is not empty
if ( ! empty( $this->media_fields ) )
// Browser those fields
foreach ( $this->media_fields as $field => $values )
// If this field has been submitted (is present in the $attachment variable)
if ( isset( $attachment[$field] ) )
// If submitted field is empty
// We add errors to the post object with the "error_text" parameter we set in the options
if ( strlen( trim( $attachment[$field] ) ) == 0 )
$post['errors'][$field]['errors'][] = __( $values['error_text'] );
// Otherwise we update the custom field
else
update_post_meta( $post['ID'], '_' . $field, $attachment[$field] );
// Otherwise, we delete it if it already existed
else
delete_post_meta( $post['ID'], $field );
}
}
return $post;
}
Ok, now our custom fields are saved into the database and will be available for the front-end.
Please be careful when manipulating the post parameter in both hooks. It is an object in the first one and an array in the second one.
Tip: the update_post_meta will create the meta if it doesn’t exist.
Tip: We prefix the custom field key with an underscore “_” so that they won’t be listed in the custom fields metaboxes on post edit pages.
Error Considerations
As of version 3.5, it seems that errors still don’t appear on attachment edit forms. I tried to investigate the core code, and despite the fact it should have been fixed (http://core.trac.wordpress.org/ticket/13810), it seems not.
For the ajax save process, it is certain it’s not done yet as mentionned in the ajax-actions.php file:
$errors = $post['errors']; // @todo return me and display me!
So right now, errors are not going to work properly, but the code is done so that when those bugs are fixed, it’ll work.
/>
Front End
To use those custom fields in your templates, you just have to retrieve post metas the same way you would for regular posts. Don’t forget to add the “_” prefix to the custom fields’ keys.
The WordPress search form doesn’t offer any bells and whistles by default. If it’s already included in your theme, or you’ve added the search widget to one of your sidebars, you can attest to that. One way to greatly improve its functionality is to include an autocomplete script to help enhance the efficiency of how relevant search queries are relayed.
/>
Twitter typeahead.js
There are quite a few autocomplete scripts available and recently Jake Harding from Twitter released typeahead.js, a completely independent version of a similarly named script that comes packaged with Bootstrap. I thought it would be interesting to figure out how to use this lightweight script with WordPress, and after a bit of fumbling around, I managed to put together a little plugin with the help of Michal Bluma.
/>
WP Typeahead Plugin
The plugin is pretty straightforward since there’s only a little bit of customization that is needed to get things working properly. I’ll break down each section of the plugin code for you to explain what’s going on.
On its own, the above code will only spit out some errors but this is the start of everything that you need to use typeahead.js with the WordPress search form. The first action is there to enqueue the JavaScript / CSS files you need and place the required JS in the footer. Next come the Ajax calls to help out with the search results. Let’s take a look at each function.
There are four files that need to be enqueued. First is the actual typeahead.js file, then the templating engine called hogan.js, followed by a new JavaScript file we’ll create to put everything in motion, and finally the stylesheet that makes it all look good.
You’ll notice in the middle there we also use wp_localize_script to make the Ajax URL available for our JavaScript.
Put this into the new /js/wp-typeahead.js file. The jQuery selector above will attach the typeahead function to any of the default WordPress search forms and use the Hogan templating engine to format the returned Ajax data. Sometimes, the search form can be modified by your theme and the submit button will be removed so I’ve added in a little script to make sure that when you hit the enter button, the search form is actually submitted.
The Ajax Query
/**
* Ajax query for the search
*
* @since 1.0.0
*/
public function ajax_search()
if ( isset( $_REQUEST['fn'] ) && 'get_ajax_search' == $_REQUEST['fn'] )
$search_query = new WP_Query( array(
's' => $_REQUEST['terms'],
'posts_per_page' => 10,
'no_found_rows' => true,
) );
$results = array( );
if ( $search_query->get_posts() )
foreach ( $search_query->get_posts() as $the_post )
$title = get_the_title( $the_post->ID );
$results[] = array(
'value' => $title,
'url' => get_permalink( $the_post->ID ),
'tokens' => explode( ' ', $title ),
);
} else
$results[] = __( 'Sorry. No results match your search.', 'wp-typeahead' );
wp_reset_postdata();
echo json_encode( $results );
}
die();
}
When something is typed into the search form, typeahead.js will take it and submit it through Ajax using the remote parameter from the code in the last step. That text has to pass through a function in order for it to be useful and that’s why you need the little snippet above.
It takes the search text, runs it through a WordPress query to return any relavent results if they exist. Those results are sent back after being encoded using JSON so that the script can read the data properly.
/>
The Completed Code
With everything in place, the main plugin file should look like this…
When you download the plugin, you’ll have the stylesheet and required JS files included within the ZIP file.
/>
Conclusion
Adding an autocomplete script to your search form can help your users navigate through your site more easily. That means a better overall experience which will hopefully lead to more repeat visits and higher traffic. This plugin just needs to be activated in order for it to work with your search forms.
If you have any comments or feedback on anything you read above, please feel free to discuss it below.
Original from: http://feedproxy.google.com/~r/Wptuts/~3/p0PvD5csT4U/
In this series, we’re discussing how to implement Ajax in the WordPress frontend. In the first post in the series, we reviewed how Ajax works at a high-level, reviewed how to introduce Ajax into the Dashboard of WordPress, and reviewed the two hooks available for incorporating Ajax into WordPress.
At this point, it’s time to actually build something that will demonstrate how we can use Ajax in the WordPress frontend. To do this, we’ll be writing our own plugin making sure that we’re following WordPress best practices along the way.
By the end of this article, we’ll have a fully working plugin with source code publicly available on GitHub. With that said, let’s get started.
/>
Planning It Out
If you’ve read any of my previous articles, then you know that I always like to begin my projects with planning out what we’re going to do. This project is no different.
In this example, we’re going to be introducing a checkbox that allows readers who are logged into a WordPress site to check off blog posts that they’ve read. This way, they’ll only see posts that they’ve yet to read since logging into the site.
To build this, we’ll be using a couple of things:
A fresh install of WordPress
The WordPress Theme Unit Test to provide us with plenty of example content
The Twenty Eleven theme (since it’s so widely available)
A user account who has the ‘Subscriber’ role
Once you have the environment setup, here’s the plan of action that we’ll be following for our plugin:
We’ll create a new plugin in the plugins directory called I’ve Read This (in the directory ive-read-this)
On each post, we’ll introduce a checkbox and a label that allows users to mark that they’ve read this post
Once the post has been marked as read, the option will disappear from view
Got it? Go ahead and login as the user that you created with the ‘Subscriber’ role and let’s get started!
/>
Building I’ve Read This
Once you’ve got the test data imported, your setup should look something like this:
From here, we’re ready to get started writing the plugin.
Stubbing Out the Plugin
Before we actually write any code, I like to go ahead and stub out the plugin files. This means that we’ll setup the directory, the basic plugin structure, and any directories that we may need to use for plugin dependencies.
Since we’ll be providing some light styling as well as JavaScript files for initiating the Ajax request, here’s what the basic directory structure should look like. The lang directory is optional, though I consider it a best practice:
Now, let’s stub out the text required for the plugin.php. Note that this will be nothing but a skeleton. It will be primarily responsible for laying the foundation for what we’ll be building later in the article:
At this point, you can actually activate the plugin in the WordPress plugin dashboard, though nothing will actually happen. If you’re up for it, go ahead and do that now – you’ll be able to watch the plugin come to life as we work on it.
Introduce a Checkbox on Each Post
Since we’re going to be introducing a checkbox on each post that allows users to toggle whether or not they’ve read the post, we’ll need to account for the following:
We need to make sure that the checkbox is only displayed when the user is logged in
The checkbox should be at the bottom of the post on the single post page since that’s where user’s will mark that they’ve read the post
We can achieve both of these by adding the following function:
/**
* Adds a checkbox to the end of a post in single view that allows users who are logged in
* to mark their post as read.
*
* @param $content The post content
* @return The post content with or without the added checkbox
*/
public function add_checkbox( $content )
// We only want to modify the content if the user is logged in
if( is_user_logged_in() && is_single() )
// Build the element that will be used to mark this post as read
$html = '
';
$html .= '';
$html .= '
';
// Append it to the content
$content .= $html;
// end if
return $content;
} // end add_checkbox
Read the comments carefully as they should explain exactly what’s going on; however, if you’re unclear, don’t hesitate to leave a comment.
Next, we need to add the following line in the constructor so that the_content filter is called:
// Setup the action for rendering the checkbox
add_filter( 'the_content', array( &$this, 'add_checkbox' ) );
Finally, let’s add a little bit of style just to give the checkbox a slightly unique look and feel within the context of the Twenty Eleven theme. In the plugin’s plugin.css file, add the following code:
Now, if you log into the WordPress installation and navigate to the bottom of a single post, you should see something like the following image:
At this point, we’re ready to begin writing some JavaScript.
Making a Request: Setup the Click Handler for the Checkbox
The first thing that we need to do is to setup the JavaScript so that it only fires if the “I’ve Read This” container is on the page. There are a variety of ways to do this, but since we’re loading the JavaScript on every page, then we’ll use JavaScript to check for the presence of the “I’ve Read This” check box that we’re writing out to the page.
To do this, add the following code to plugin.js. The code comments should be self-explanatory. If not, leave a comment!
(function ($)
$(function ()
// If the "I've Read This Container" is on this page, let's setup the event handler
if(1 === $('#ive-read-this-container').length)
// end if
});
}(jQuery));
In the code that you see above, anything that we place within the conditional will only fire if the “I’ve Read This” container element is present.
In this case, we know that we need to send the ID of the post to the server. Since the user is logged in, we’ll be able to get his/her ID on the server side.
So, the next step is to get the ID of the post that we’re on. Luckily, Twenty Eleven stores the number of the post in the article element’s ID. We just need to parse it out.
Let’s do that now:
// We use the change attribute so that the event handler fires
// whenever the checkbox or its associated label are clicked.
$('input[name="ive-read-this"]').change(function (evt)
// We can retrieve the ID of this post from the 's ID. This will be required
// so that we can mark that the user has read this particular post and we can hide it.
var sArticleId, iPostId;
// Get the article ID and split it - the second index is always the post ID in Twenty Eleven
sArticleId = $("article").attr('id');
iPostId = parseInt(sArticleId.split('-')[1]);
);
At this point, we’re ready to setup an Ajax request. We’ll be using jQuery’s $.post method for doing this and we’ll be using WordPress’ standard ajaxurl to handle our response.
Handling the Event: Mark the Post as Read
Let’s go ahead and write the code that will send the ID of the post across. We’ll worry about the response later in this article, hence the “TODO” comment in the code.
// Initial the request to mark this this particular post as read
$.post(ajaxurl,
post_id: iPostId
, function (response)
// TODO
);
At this point in development, the full JavaScript source should look like this:
(function ($)
$(function ()
// If the "I've Read This Container" is on this page, let's setup the event handler
if(1 === $('#ive-read-this-container').length)
// We use the change attribute so that the event handler fires
// whenever the checkbox or its associated label are clicked.
$('input[name="ive-read-this"]').change(function (evt)
// We can retrieve the ID of this post from the 's ID. This will be required
// so that we can mark that the user has read this particular post and we can hide it.
var sArticleId, iPostId;
// Get the article ID and split it - the second index is always the post ID in Twenty Eleven
sArticleId = $("article").attr('id');
iPostId = parseInt(sArticleId.split('-')[1]);
// Initialise the request to mark this particular post as read
$.post(ajaxurl,
post_id: iPostId
, function (response)
// TODO
);
});
} // end if
});
}(jQuery));
For those of you who have been working through the example code as you’ve read the article, you’ll immediately notice that your browser throws a console error:
Uncaught ReferenceError: ajaxurl is not defined
Oops! And this is where we need to make sure to properly include WordPress’ Ajax library.
Including WordPress’ Ajax Library on the Frontend
To do this, we’ll need to hook into the wp_head action. Add the following line of code in the constructor of your plugin:
// Include the Ajax library on the front end
add_action( 'wp_head', array( &$this, 'add_ajax_library' ) );
Next, add the following function. This is what’s actually responsible for including the Ajax library:
/**
* Adds the WordPress Ajax Library to the frontend.
*/
public function add_ajax_library()
$html = '';
echo $html;
// end add_ajax_library
Now, if you try to execute the code, you should have no problem. At this point, we’re ready to keep going.
Handle the Event: Mark the Post as Read
Now that we’ve got the request being sent to the server, we can write our server-side event handler. This is how the handler should operate:
Check that the incoming Post ID value is set and that it’s a numeric value (this is very rudimentary spoof protection, but it works for all intents and purposes).
Next, try to update the current user’s meta using his/her ID and the post ID.
If the update fails, we’ll return -1; otherwise, we’ll return 1. We’ll handle these values in the response handler in the JavaScript.
First, we’ll add the hook in the constructor of the plugin:
// Setup the event handler for marking this post as read for the current user
add_action( 'wp_ajax_mark_as_read', array( &$this, 'mark_as_read' ) );
Next, we’ll actually implement the handler:
/**
* Uses the current user ID and the incoming post ID to mark this post as read
* for the current user.
*
* We store this post's ID in the associated user's meta so that we can hide it
* from displaying in the list later.
*/
public function mark_as_read()
// First, we need to make sure the post ID parameter has been set and that it's a numeric value
if( isset( $_POST['post_id'] ) && is_numeric( $_POST['post_id'] ) )
// If we fail to update the user meta, respond with -1; otherwise, respond with 1.
echo false == update_user_meta( wp_get_current_user()->ID, $_POST['post_id'], 'ive_read_this' ) ? "-1" : "1";
// end if
die();
} // end mark_as_read
To that end, let’s revisit the outstanding TODO in the response function of the JavaScript that we were working on. Here’s the full script:
(function ($)
$(function ()
// If the "I've Read This Container" is on this page, let's setup the event handler
if(1 === $('#ive-read-this-container').length)
// We use the change attribute so that the event handler fires
// whenever the checkbox or its associated label are clicked.
$('input[name="ive-read-this"]').change(function (evt)
// We can retrieve the ID of this post from the 's ID. This will be required
// so that we can mark that the user has read this particular post and we can hide it.
var sArticleId, iPostId;
// Get the article ID and split it - the second index is always the post ID in Twenty Eleven
sArticleId = $("article").attr('id');
iPostId = parseInt(sArticleId.split('-')[1]);
// Initial the request to mark this this particular post as read
$.post(ajaxurl,
action: 'mark_as_read',
post_id: iPostId
, function (response)
// If the server returns '1', then we can mark this post as read, so we'll hide the checkbox
// container. Next time the user browses the index, this post won't appear
if (1 === parseInt(response))
$('#ive-read-this-container').slideUp('fast');
// Otherwise, let's alert the user that there was a problem. In a larger environment, we'd
// want to handle this more gracefully.
else
alert("There was an error marking this post as read. Please try again.");
// end if/else
});
});
} // end if
});
}(jQuery));
One More Change
If the user happens to find their way to an individual post page (such as being linked to it), we should check to see if they’ve previously marked it to be read.
To do this, we need to refactor the add_checkbox function so that it checks to see if the user is logged in and it reads the user meta to determine if the post has been previously marked as read:
/**
* Adds a checkbox to the end of a post in single view that allows users who are logged in
* to mark their post as read.
*
* @param $content The post content
* @return The post content with or without the added checkbox
*/
public function add_checkbox( $content )
// We only want to modify the content if the user is logged in
if( is_single() )
// If the user is logged in...
if( is_user_logged_in() )
// And if they've previously read this post...
if( 'ive_read_this' == get_user_meta( wp_get_current_user()->ID, get_the_ID(), true ) )
// Build the element to indicate this post has been read
$html = '
';
// Otherwise, give them the option to mark this post as read
else
// Build the element that will be used to mark this post as read
$html = '
';
$html .= '';
$html .= '
';
// end if
// Append it to the content
$content .= $html;
} // end if
} // end if
return $content;
} // end add_checkbox
See It in Action!
At this point, you’ve got a working plugin:
You should be able to navigate to any post
If you’ve not read it, then you should be able to click on the checkbox and have it disappear
If you reload the page, then you’ll see the notification that the post has been marked as read.
Not bad, right?
Of course, there’s always room to experiment on your own with this. For example, you could work on excluding these posts from the main loop if they’ve been marked as read. Another option would be to add a custom classname and then styling the post to indicate that the current user has read it.
Finally, remember that you can grab all of the source code in its entirety on GitHub.
In this two part series, we’re taking a look at how to properly introduce Ajax-specific functionality into the WordPress Dashboard.
In the first article in the series, we began working on a plugin that displays a notification as soon as it’s activated … but that’s it. In this article, we’ll add Ajax-enabled functionality that will allow users to dismiss the message and we’ll finish up with a working version of the plugin.
Specifically, we’re going to cover all of the things necessary on both the server-side and the client-side that are necessary to process an Ajax request and respond appropriately.
Finally, we’ll review a checklist of items that all Ajax-based WordPress functionality should have to make sure that you properly employ the API in future projects.
Remember the Nonce
Before we get started, it’s important to make sure that you have the nonce value in the function that renders your notification method. For review, here’s the function that we included in the first article:
public function display_admin_notice()
$html = '
';
$html .= '
';
$html .= __( 'The Ajax Notification example plugin is active. This message will appear until you choose to dismiss it.', 'ajax-notification' );
$html .= '
Notice that we’re rendering the nonce value using wp_create_nonce in a span element having the ID of ajax-notification-nonce. I bring this up for three reasons:
Nonce values provide security measures and are important when you’re making any type of request from the front-end to the back-end.
In my experience, this is one of the things that developers most often leave out of their work – this is meant to make sure we have this covered prior to writing any additional code.
The element containing the nonce value needs a specific ID so that we can easily access it using JavaScript when initiating our Ajax request.
With that, let’s get to writing the Ajax functionality.
On to Ajax
Building Ajax-based functionality in the WordPress Dashboard typically includes four key points:
Some JavaScript functionality that will respond to the user’s event and send it to the server
A server-side callback function that is responsible for managing the request coming from the browser
Server-side functionality that will send the data back to the browser
JavaScript functionality responsible for handling the response
Though there’s no particular order in which we need to write this code, we’ll just go down the list as it’s stated above and work through it.
Sending the Request
The JavaScript code for sending the request is relatively boilerplate stuff, but we need to first outline what it is that we’re actually going to do:
The user decides to dismiss the notification
The user clicks on the dismiss anchor that we’ve provided
JavaScript responds to the event when the user clicks on said anchor
JavaScript sends a request to the server
We’ll write the code incrementally to make sure that it’s easy to follow along. First, we’ll start by setting up the code after the window has loaded and we’ll make sure that the Ajax notification message is present:
(function ($)
$(function ()
// Check to see if the Ajax Notification is visible; otherwise,
// we won't worry about doing any of this.
if ($('#dismiss-ajax-notification').length > 0)
// Stuff TODO here...
);
});
}(jQuery));
Next, we need to setup an event handler that will fire once the user clicks on the anchor that we’ve placed in the notification. For this, we need the ID of the message’s element – that is, dismiss-ajax-notification.
Because an anchor’s default behavior is to try to navigate to its href attribute, we need to also prevent the default action from occurring.
(function ($)
"use strict";
$(function ()
// Check to see if the Ajax Notification is visible
if ($('#dismiss-ajax-notification').length > 0)
// If so, we need to setup an event handler to trigger it's dismissal
$('#dismiss-ajax-notification').click(function (evt)
evt.preventDefault();
// More TODO here...
);
} // end if
});
}(jQuery));
At this point, we’re ready to actually send the request to the server. To do this, we’ll be using the jQuery post function. We’ll be passing it three arguments:
The URL of the address to which the request should be sent. This is a global value provided by WordPress. It’s stored in the ajaxurl variable
The hash of options to send to the server. This includes the action – or the function – to fire on the server and the nonce value for validation
The function used to handle the response
Let’s write out all of this now (including stubbing out the response function) and then we’ll hop over to the server-side code.
(function ($)
$(function ()
// Check to see if the Ajax Notification is visible
if ($('#dismiss-ajax-notification').length > 0)
// If so, we need to setup an event handler to trigger it's dismissal
$('#dismiss-ajax-notification').click(function (evt)
evt.preventDefault();
// Initiate a request to the server-side
$.post(ajaxurl,
// The name of the function to fire on the server
action: 'hide_admin_notification',
// The nonce value to send for the security check
nonce: $.trim($('#ajax-notification-nonce').text())
, function (response)
// TODO response handler
);
});
} // end if
});
}(jQuery));
Recall earlier that I said we’d need to know the ID of the field containing the nonce value – that is, ajax-notification-nonce. Notice above that we’re grabbing the text value of that element and sending it to the server as the value of the nonce key.
The second thing to notice is that we’re sending along an action key that has the value of hide_admin_notification. This is a function that we need to write on the server as it’s what will be responsible for actually hiding the notification.
Handling the Request
In our plugin file, we need to create a function that has the name as the action value mentioned above: hide_admin_notification.
As usual, I like to talk about what the function is going to do before writing any code. In this case, here’s what needs to be done:
We need to make sure the incoming nonce is correct; otherwise, we don’t want to execute any code
We need to update the option that we created in the first article to set the dismiss to false
We need to send a value back to the browser so that it can respond appropriately to the function
Here’s the code for making that happen:
public function hide_admin_notification()
// First, check the nonce to make sure it matches what we created when displaying the message.
// If not, we won't do anything.
if( wp_verify_nonce( $_REQUEST['nonce'], 'ajax-notification-nonce' ) )
// If the update to the option is successful, send 1 back to the browser;
// Otherwise, send 0.
if( update_option( 'hide_ajax_notification', true ) )
die( '1' );
else
die( '0' );
// end if/else
} // end if
}
It’s relatively simple, isn’t it? The key thing to understand is that we’re sending the value of ’1′ in the context of die if the option is successfully updated; otherwise, we send the value of ’0′. This will allow us to read the value in the response on the browser to determine how best to respond.
Obviously, if the returned value is 1, then we can hide the notification.
Before hopping back into the JavaScript, we need to make sure that we wire this function up using the appropriate hook. So, in the plugin’s constructor, let’s add a line for add_action:
The key thing to note here is that the tag for the function is labeled ‘wp_ajax_hide_admin_notification‘.
If you’re working with Ajax in the WordPress dashboard, then your hook must be added with the wp_ajax_ prefix and it should end with the name of the function.
This is easily the second most important thing I see developers miss when working on Ajax-based code.
From here, we’re ready to hop back into the client-side code.
Handling the Response
Finally, we’re ready to handle the response. This is easy: If the server responds with a 1, then we’ll hide; otherwise, we won’t do anything.
Granted, the best practice would be to display an error message or some type of feedback to let the user know that something went wrong, but the main point of the article is to demonstrate Ajax in WordPress so we’ll simply change out the class name from updated to error.
Here’s what needs to be added to the JavaScript source to handle the response:
function (response)
// If the response was successful (that is, 1 was returned), hide the notification;
// Otherwise, we'll change the class name of the notification
if ('1' === response)
$('#ajax-notification').fadeOut('slow');
else
$('#ajax-notification')
.removeClass('updated')
.addClass('error');
// end if
}
And that’s really it. The full JavaScript source should look like this:
(function ($)
$(function ()
// Check to see if the Ajax Notification is visible
if ($('#dismiss-ajax-notification').length > 0)
// If so, we need to setup an event handler to trigger it's dismissal
$('#dismiss-ajax-notification').click(function (evt)
evt.preventDefault();
// Initiate a request to the server-side
$.post(ajaxurl,
// The name of the function to fire on the server
action: 'hide_admin_notification',
// The nonce value to send for the security check
nonce: $.trim($('#ajax-notification-nonce').text())
, function (response)
// If the response was successful (that is, 1 was returned), hide the notification;
// Otherwise, we'll change the class name of the notification
if ('1' === response)
$('#ajax-notification').fadeOut('slow');
else
$('#ajax-notification')
.removeClass('updated')
.addClass('error');
// end if
});
});
} // end if
});
}(jQuery));
And the plugin’s PHP should look like this:
/*
Plugin Name: Ajax Notification
Plugin URI: http://github.com/tommcfarlin/ajax-notification
Description: An example plugin used to demonstrate the WordPress Ajax API for a companion article on Envato's WPTuts+ site.
Version: 1.0
Author: Tom McFarlin
Author URI: http://tommcfarlin.com
Author Email: tom@tommcfarlin.com
License:
Copyright 2012 Tom McFarlin (tom@tommcfarlin.com)
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License, version 2, as
published by the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
class Ajax_Notification
/*--------------------------------------------*
* Constructor
*--------------------------------------------*/
/**
* Initializes the plugin by setting localization, filters, and administration functions.
*/
function __construct()
load_plugin_textdomain( 'ajax-notification', false, dirname( plugin_basename( __FILE__ ) ) . '/lang' );
register_activation_hook( __FILE__, array( &$this, 'activate' ) );
register_deactivation_hook( __FILE__, array( &$this, 'deactivate' ) );
add_action( 'admin_enqueue_scripts', array( &$this, 'register_admin_scripts' ) );
// Display the admin notice only if it hasn't been hidden
if( false == get_option( 'hide_ajax_notification' ) )
add_action( 'admin_notices', array( &$this, 'display_admin_notice' ) );
// end if
add_action( 'wp_ajax_hide_admin_notification', array( &$this, 'hide_admin_notification' ) );
} // end constructor
/*--------------------------------------------*
* Core Functions
*---------------------------------------------*/
/**
* Upon activation, add a new option used to track whether or not to display the notification.
*/
public function activate()
add_option( 'hide_ajax_notification', false );
// end activate
/**
* Upon deactivation, removes the option that was created when the plugin was activated.
*/
public function deactivate()
delete_option( 'hide_ajax_notification' );
// end deactivate
/**
* Registers and enqueues admin-specific minified JavaScript.
*/
public function register_admin_scripts()
wp_register_script( 'ajax-notification-admin', plugins_url( 'ajax-notification/js/admin.min.js' ) );
wp_enqueue_script( 'ajax-notification-admin' );
// end register_admin_scripts
/**
* Renders the administration notice. Also renders a hidden nonce used for security when processing the Ajax request.
*/
public function display_admin_notice()
$html = '
';
$html .= '
';
$html .= __( 'The Ajax Notification example plugin is active. This message will appear until you choose to dismiss it.', 'ajax-notification' );
$html .= '
';
echo $html;
// end display_admin_notice
/**
* JavaScript callback used to hide the administration notice when the 'Dismiss' anchor is clicked on the front end.
*/
public function hide_admin_notification()
// First, check the nonce to make sure it matches what we created when displaying the message.
// If not, we won't do anything.
if( wp_verify_nonce( $_REQUEST['nonce'], 'ajax-notification-nonce' ) )
// If the update to the option is successful, send 1 back to the browser;
// Otherwise, send 0.
if( update_option( 'hide_ajax_notification', true ) )
die( '1' );
else
die( '0' );
// end if/else
} // end if
} // end hide_admin_notification
} // end class
new Ajax_Notification();
Conclusion
You can grab the plugin on GitHub. For reference, be sure to review the following resources:
Not long ago, Ajax was all the rage – the idea of updating part of a page without actually needing to reload the entire page was awesome, remember?
But it’s been a few years and now it’s practically the standard – it’s hard to think about your favorite web application reloading an entire page to complete a task, isn’t it?
Depending on your background, there are a number of different ways to implement Ajax. In this series, we’re going to do a very brief overview of what Ajax is, how it works, and then how to properly use it within the WordPress administration dashboard.
Ajax: The Short of It
Ajax is a technology that’s typically viewed as an acronym for “Asynchronous JavaScript and XML” but it’s really more than that. Generally speaking, Ajax is what we do when we update part of a page (that is, without refreshing the entire thing).
At a high-level, the process looks like this:
A user performs an event – such as a mouse click – on an element in a page
The developer has written a function that listens for that event
When the event occurs, the function sends data from the browser back to the server
The server then performs an action and/or gathers any requested data and returns it in a specific format
Although data used to be returned in XML, now it’s more common to return JSON, HTML fragments, or even basic strings.
On top of that, in the past browsers implemented the underlying facilities for performing Ajax-based functions a bit differently, so building Ajax-enabled applications required a significant amount of code just to handle the variety of browsers.
Luckily, libraries such as jQuery have made this process much easier by providing a level of abstraction that takes away the drudgery of handling cross-browser inconsistencies allowing us to focus solely on sending and receiving data asynchronously.
Since WordPress ships with jQuery, we have the advantage of being able to piggy-back on top of that library for our work. But that’s not all – although it’s possible to roll your own system for Ajax functionality within WordPress, the platform actually provides a framework for doing it very easily.
Ajax in the WordPress Dashboard
The framework that WordPress provides for introducing Ajax-based functionality is actually a very simple process. First, I’ll define it, then we’ll look at each step in more detail.
Create an element that will be used to trigger the Ajax request
Write JavaScript code to handle the event when the input element’s state changes (such as clicked, typed, etc.)
On the server-side, process the request and prepare a response to return to the browser
Once again, use JavaScript to handle the response accordingly
Four steps – that’s it. Not bad, right? Throughout the remainder of this article, we’ll take a look at a practical example of doing exactly this.
Ajax Notification: An Example Plugin for WordPress
In our example, we’re going to write a plugin that displays a notification message as soon as the plugin is activated. That’s its sole purpose: to simply show that it’s active.
Simple? Sure. Pointless? From a functionality aspect, definitely. But we’ll be covering a lot of ground that can contribute directly back to practical work: We’ll discuss administration notices, nonce values, the WordPress Ajax API, options, and JavaScript-based responses.
Plan the Plugin
Before writing any code, let’s plan how the plugin is going to work:
When the plugin is activated, it should create an option value for storing whether or not the user has selected to hide the message
When the plugin is deactivated, it should remove the option from the database completely
The notification message can display a simple message and should be styled with the native WordPress UI
There should be an element that the user can click to dismiss the message
If the user opts to hide the message, it should hide without refreshing the page and should be hidden from this point forward
Easy enough, I think. Here’s a simple sketch of what the UI of the plugin will look like:
At this point, it’s time to write code.
Create the Options
Though the full plugin will be linked at the end of the post, we’ll be looking at the plugin as we begin development. Let’s setup the basic structure of the plugin so that it’s displaying a notification when it’s activated.
In order to determine whether or not the user wants to display the notification message, we need to create an option that will store the value. Similarly, we need to delete this value whenever the plugin is deactivated – there’s no sense in leaving old data around, right?
To do this, we’ll register two hooks: one for activation and one for deactivation.
Let’s define the class and the constructor that includes actions for these two methods:
class Ajax_Notification
function __construct()
register_activation_hook( __FILE__, array( &$this, 'activate' ) );
register_deactivation_hook( __FILE__, array( &$this, 'deactivate' ) );
}
new Ajax_Notification();
Of course, nothing will actually happen at this point as we haven’t defined the two methods. Let’s do that now:
function activate()
add_option( 'hide_ajax_notification', false );
// end activate
function deactivate()
delete_option( 'hide_ajax_notification' );
// end deactivate
The functions should be relatively clear, but here’s a quick explanation of what we’re doing:
activate is adding an option to the database with the key hide_ajax_notification. Because we want to show the notification until the user says otherwise, we’ll set it to false.
deactivate simply deletes the option from the database.
Now we just need a message to display.
Create the Notification Message
Let’s add another hook into the constructor that will call an action that will actually display a notification message. The updated constructor will look like this:
class Ajax_Notification
function __construct()
register_activation_hook( __FILE__, array( &$this, 'activate' ) );
register_deactivation_hook( __FILE__, array( &$this, 'deactivate' ) );
add_action( 'admin_notices', array( &$this, 'display_admin_notice' ) );
}
new Ajax_Notification();
Of course, nothing will actually happen yet – we need to define a method display_admin_notice that will be responsible for rendering the message. So let’s define that now:
function display_admin_notice()
$html = '
';
$html .= '
';
$html .= 'The Ajax Notification example plugin is active. This message will appear until you choose to dismiss it.';
$html .= '
Above, we’re creating an element that will display a simple message:
The Ajax Notification example plugin is active. This message will appear until you choose to dismiss it.
The message also provides an anchor that will allow users to dismiss the message. The import thing to note about the anchor is this:
The href attribute is an empty javascript:; statement because the message isn’t really linking anywhere
The anchor has an ID so that we can easily access the link using JavaScript later in the article
Of course, you could introduce an href to the anchor in case the user doesn’t have JavaScript enabled, but this article is about Ajax so we’re assuming that JavaScript is enabled. Progressive enhancement is a whole other topic.
The second thing that you’ll notice is that I’ve included a call to wp_create_nonce. This is a security measure. When the user clicks on the ‘dismiss’ anchor, we’ll be able to validate that the request is coming from the notification message; otherwise, we can ignore the request.
The method takes in a single value that is used to identify the nonce. In our case, it’s ajax-notification-nonce. We’ll be revisiting this value once we begin introducing the Ajax functionality.
Conclusion
By now, you have a fully working – albeit static – plugin. When you activate the plugin, you should see a message similar to the one below:
In the next article, we’ll introduce Ajax functionality and we’ll end with a checklist of things that all WordPress-based Ajax functionality should have, but in the mean time be sure to check out the following resources:
Ajax Notification 0.1. A working version of the plugin as developed in this article.
WordPress has a good posting system which is extendable so that WordPress can be used to build a lot of different sites rather than just a blog. WordPress also has a very extendable commenting system. The commenting system of WordPress can also be extended in different ways to be used in your WordPress sites. The commenting system can be used as a review forum if the WordPress site is to be made into a product catalog system. The commenting system can be used as answers to questions if the WordPress site is to be used for a Question and Answer site. So the commenting system in WordPress can be moulded or extended to provide functionality th at can enhance the complete site built on WordPress. In this article we are going to write a plugin to add a voting system on the comments which could be useful if the commenting system is used in a different way like in the examples stated above and many others that you can think up.
Step 1 Creating the Plugin
Let’s now start by creating the plugin. In our wp-content folder we will create a folder for our plugin called commentsvote. Inside the folder commentsvote create a file commentsvote.php which will be the main file of our plugin. Then we will add the plugin header as follows which will help WordPress to identify our plugin and show it in the plugin list in WordPress’ admin. The header is as follows.
Once we add the header we will be able to see our plugin in the plugin list as follows. We can now activate the plugin.
Now let’s setup some variables and scripts which we will use in our plugin. We create constants to define the plugin path and the plugin URL which can be used in different places in the plugin as follows.
Also as we are going to have the functionality to add votes via AJAX we will need a JavaScript file. To add the JavaScript file we create a js folder in our plugin folder and create a commentsvote.js file in it. Once we have created the necessary files our folder structure for the plugin will look as follows.
Then we enqueue the scripts so that the JS files are loaded by the WordPress engine as follows.
Step 2 Understanding Some WordPress Function for Comments
WordPress provides support for comments meta in which we can store and retrieve some meta data related to the comment. We are going to store the votes on the comments as comment meta using these supporting functions. Hence here we are going to see what these functions are which WordPress provides.
The first function which we are going to see is get_comment_meta(). This function is similar to get_post_meta(). This function takes the first argument as the comment ID, the second argument as the name of the meta key, the third argument which if set to true returns the value as a string, if set to false or left blank will return an array of all the values for that key.
For more information you can visit the get_comment_meta() page in the WordPress Codex.
The other function which we are going to use is update_comment_meta. This function takes four arguments which are the comment ID, the meta key, the meta value and the previous value.
For more information you can visit the update_comment_meta() page in the WordPress Codex.
Step 3 Displaying the Current Votes Next to the Comment
Now let’s add the number of votes and a vote link next to each comment so that the users can vote on the comments. For this first we write a function which will create the link and return it as a string.
In this function we first get the current comment ID using the WordPress function get_comment_ID(). Then we get the number of votes on comment the using the function get_comment_meta().
Then we create a link in which we call the JavaScript function commentsvote_add() which we will implement in the below steps.
Then let’s add this link to every comment using the filter comment_text. We hook into the filter comment_text and add the link as follows.
Now if you visit the individual post page you will see the vote’s link as follows.
Step 4 Creating the AJAX Handler for Adding Votes on Comments
Now once we have created the code to show the link let’s create the AJAX handlers in WordPress to handle the request. The AJAX request handler is as follows.
In the AJAX handler we first verify the nonce. Then we get the comment ID and get the number of current votes on the comment using the function get_comment_meta(). Once that is done we increment the current count by one and then update the meta using the function update_comment_meta().
Then we return the updated value back from the AJAX handler.
Step 5 Voting on Comments via AJAX
Now once our link and the AJAX handlers are done we just need to write the JavaScript function to make the AJAX call. The function is as follows.
The function basically gets the comment ID and the makes an AJAX call to the AJAX handler. Once the AJAX handler returns the value the JavaScript function retrieves the div of the comment and updates its content with the new number of votes. Now one can click on the vote to add one vote to the comment.
Step 6 Allowing Only Logged in Users to Vote
Now let’s enhance the plugin to give an option to the admin to allow only logged in users to vote on comments. To do this we first create a settings page for our plugin. Following is the code to create a settings page.
Now depending on the setting we will check whether the user is logged in or not before showing the vote link or make the link point to the login page. So the adapted functions commentsvote_showlink() and commentsvote_ajaxhandler() will look as follows.
So now in case if the admin makes it compulsory that logged in users can only vote and if the logged in user is not logged in he will be pointed to the login page as follows.
Step 7 Showing Most Vote Comments on the Post
Now let’s add the functionality to show below each post its top voted posts. To do this we will first have to fetch the comments for the post in descending order of its votes. There is no direct way to sort comments on the basis of their meta hence we will write a custom query for the same. We will write the following function to do it.
function commentsvote_get_top_voted_comments($post_id)
$commentids = array();
global $wpdb;
$request = "
select * from $wpdb->comments , $wpdb->commentmeta where
$wpdb->comments.comment_post_ID = ".$post_id.
" AND $wpdb->comments.comment_ID = $wpdb->commentmeta.comment_ID
AND $wpdb->commentmeta.meta_key = '_commentsvote'
ORDER BY $wpdb->commentmeta.meta_value+0 DESC;
";
$comments = $wpdb->get_results($request);
foreach ($comments as $comment)
array_push( $commentids , $comment->comment_ID );
return $commentids;
}
This function takes posts as input and then runs a custom query on the wp_comments and wp_commentmeta to fetch the list of top voted comments for the post.
Then we add a function to the filter the_content as follows to show the comment excerpt and the votes below the post.
function show_top_voted_comments($content)
$result = "";
$post_ID = get_the_ID();
$commentids = commentsvote_get_top_voted_comments($post_ID);
if (count($commentids) > 0 )
$result = "Top Comments for this post: ";
foreach ($commentids as $commentid)
$votecount = get_comment_meta($commentid, '_commentsvote', true) != '' ? get_comment_meta($commentid, '_commentsvote', true) : '0';
$result .=get_comment_excerpt($commentid) .'('.$votecount.')'.' ';
return $content.$result;
}
add_filter('the_content', show_top_voted_comments);
Now if we see the post it will look as follows.
Conclusion
In case WordPress is used for different kind of sites its basic system and functionalities might not be enough for the site. But as the WordPress system is very extendable we can write plugins like the above to provide extra functionality to suit our needs. So have fun while extending your WordPress site!
Original from: http://wp.tutsplus.com/tutorials/plugins/creating-a-plugin-to-add-votes-to-your-wordpress-comments-using-ajax/
WordPress basically divides itself into two portions, the front end section where people can come and read posts or articles on the site. The other is the WordPress admin section from which one can create posts and pages. This works very well if WordPress is used as a general blogging site. But as WordPress is used for different kinds of sites it sometimes becomes necessary to give the user a way to create posts from the front end of the site without forcing him to go in the WordPress admin section.
In this tutorial we are going to see how to create a widget to let users create posts from the front end. This will help the users of the site to create content.
Step 1 Creating the Plugin
To create a plugin, create a file ajaxpostfromfront.php in your wp-content/plugins/ajaxpostfromfront folder. To create a plugin in WordPress we have to add the plugin header as follows:
/*
Plugin Name: Ajax post from front
Plugin URI:
Description:Allows to post from front end
Author: Abbas Suterwala
Version:
Author URI:
*/
We will also define some named constants for our plugin base URL and the plugin path as follows:
This will help us to use them easily where needed in the plugin. Also create a js folder in your ajaxpostfromfront folder and add a file apf.js in it. So the folder structure of the plugin would be as follows:
We will now enqueue the scripts by hooking on to the action hook ‘wp_enqueue_scripts‘ and enqueue our javascript file and localize it to store the WordPress ajax URL which we will use for our ajax calls.
If everything has gone right until now we will be able to see our plugin in the plugin list and we should activate it.
Step 2 Understanding the WordPress Functions to Create a New Post
WordPress has a rich set of APIs or functions which are exposed to perform tasks for plugins. It has functions for all types of tasks like creating a post, creating a page, comments etc. In this plugin we are going to use the WordPress function wp_insert_post.
wp_insert_post takes in an array of the different information required to create a post in WordPress. It takes in different parameters like the post title, post content, post status, etc. It also takes in the array of categories which are to be associated with the post. It also contains some other parameters like post password and post excerpt etc.
Step 3 Creating the UI to Create Post From Front End
Next we are going to create the UI for our post from front end plugin. For this we are going to write the following function:
function apf_post_form()
?>
In the function we will first create a form using the tag. In this we will create a div with the ID apf-response which will update with the message that comes from the AJAX response we will get. Then we have created a text box for the title and a text area for the content of the post.
Next let us create a link called ‘create post’ which calls a javascript function apfaddpost which will make an AJAX call to create the post. We will see the implementation of the AJAX call in the below steps.
In case we call the function apf_post_form in the theme files you will see it as follows. In my theme I have just called it before the main loop.
Step 4 Creating a Widget to Display the UI on Front End
Now we are going to create a widget for our post from front plugin. This widget will display the UI for posting from the front which we created. Following is the code for the widget.
class AjaxPostFromFrontWidget extends WP_Widget
function AjaxPostFromFrontWidget()
// widget actual processes
$widget_ops = array('classname' => 'AjaxPostFromFrontWidget', 'description' => 'Lets you create post from front end' );
$this->WP_Widget('AjaxPostFromFrontWidget','AjaxPostFromFrontWidget', $widget_ops);
function form($instance)
// outputs the options form on admin
$defaults = array( 'title' => 'Ajax Post From Front' );
$instance = wp_parse_args( (array) $instance, $defaults );
?>
In the constructor we give the class name and the description of the widget. In the form function currently we display only one field that is the title to be displayed for the widget. We update the title field in the update function.
In the widget function we get the title saved in the widget instance and display that. Then we call the function apf_post_form which will display the form that we created in the previous step.
We will register the widget as follows:
function apf_widget_init()
// Check for the required API functions
if ( !function_exists('register_widget') )
return;
register_widget('AjaxPostFromFrontWidget');
add_action('widgets_init', 'apf_widget_init');
Now we can drag and drop our new widget on the sidebar.
Once the widget is dropped on the side bar you should be able to see the form on the home page in the sidebar as follows:
Step 5 Creating a Post via AJAX From the Front End
Now let’s create a function to handle the AJAX request of creating the post. The function to handle the AJAX request is as follows:
In this function we get the values of the title and the content from the $_POST variable. With those values using the wp_insert_post function of WordPress to create the post. The function wp_insert_post returns the newly created post id if succeeded and zero if failed. So using that value we either sent a success or a failure message back from the AJAX.
To register this function with the WordPress AJAX system we will call the following:
Once our AJAX handler is done we just need to make the AJAX request from our javascript code as follows:
function apfaddpost(posttitle,postcontent)
jQuery.ajax(
type: 'POST',
url: apfajax.ajaxurl,
data:
action: 'apf_addpost',
apftitle: posttitle,
apfcontents: postcontent
,
success: function(data, textStatus, XMLHttpRequest)
var id = '#apf-response';
jQuery(id).html('');
jQuery(id).append(data);
resetvalues();
,
error: function(MLHttpRequest, textStatus, errorThrown)
alert(errorThrown);
});
}
function resetvalues()
var title = document.getElementById("apftitle");
title.value = '';
var content = document.getElementById("apfcontents");
content.value = '';
In the function apfaddpost we just make an AJAX request passing the post title and the post content. Once the response is received we just display the message returned by the AJAX handler in the div apf-response. After that we reset the values in the form.
After clicking on create post the post will be created and the message will be seen as follows:
Step 6 Adding the Option of Letting Only Logged in Users Post
Now we will add the functionality to let the admin choose if they do not want users who are not logged in to create posts.
For this we update the apf_post_form as follows to take an argument $allowNotLoggedInuser. In that case when the user is not logged in, it will not display the form but will display a message to login.
function apf_post_form($allowNotLoggedInuser='yes')
if ( $allowNotLoggedInuser == 'no' && !is_user_logged_in() )
echo "Please Login to create new post";
return;
?>
We will also update the widget to display one more option in the form function to display a select field asking whether it is allowed for non logged in users to post. We will also update the values in the update function. In the widget function now we read the value which was set in the widget and then pass it to the apf_post_form function.
The updated widget code should look like this:
class AjaxPostFromFrontWidget extends WP_Widget
function AjaxPostFromFrontWidget()
// widget actual processes
$widget_ops = array('classname' => 'AjaxPostFromFrontWidget', 'description' => 'Lets you create post from front end' );
$this->WP_Widget('AjaxPostFromFrontWidget','AjaxPostFromFrontWidget', $widget_ops);
function form($instance)
// outputs the options form on admin
$defaults = array( 'title' => 'Ajax Post From Front','allow_not_logged_users' => 'no' );
$instance = wp_parse_args( (array) $instance, $defaults );
?>
Now from the widget are we can choose the option to whether allow logged in users or no as seen below.
Now in case the option is set to no and someone visits the home page without logging in they will see the following message to login to post.
Step 7 Adding the Option of Adding Categories to Post via Front End Widget
Now we will add the functionality to add categories to the post which we are creating from the front end. To achieve this first we will get the list of all the categories and display them as check boxes on the UI.
For this we add the following code to the function apf_post_form.
Contents
0));
foreach ( $categories as $category )
echo "";
echo $category->cat_name;
echo ' ';
?>
Create Post
The above code just gets the list of all categories and displays them as check boxes. That value is passed to our javascript function apfaddpost as an extra parameter.
In the function apfaddpost we get the values which are checked and pass it in the AJAX call as follows:
function apfaddpost ( posttitle,postcontent,postcategory )
var postCatergoryArray = new Array();
for ( var i=0; i
We will need to update the AJAX handler as follows to take the array of ids of the categories and then pass it to the wp_insert_post function , so that the newly created post have the categories appropriately.
Now if we see the widget it will be seen as follows:
And the post created will have those selected categories associated with it as seen below.
Conclusion
WordPress is an extensible platform. We can extend WordPress to add different functionality to so the WordPress platform can be used for different types of sites rather than just blogs. Like in this plugin we have added the functionality of creating posts from the front end, WordPress can be extended in different ways. So happy WordPress coding!
Original from: http://wp.tutsplus.com/tutorials/plugins/adding-posts-to-a-sites-front-end-using-ajax/
Building a WordPress plugin is not that hard, especially when you know what you’re doing. Sometimes it can get tricky though when working with multiple scripts, styles, and new functionality that sometimes requires some imagination.
In this tutorial we are going to look at a way to create a simple countdown timer plugin. We’ll look at integrating it into the WordPress installation as a widget and a shortcode in the content using settings from a meta box inside the WordPress admin editor.
A preview of the end result of this tutorial looks like this:
The Widget and Content Shortcode:
Widget and Meta-Box Admin Interface:
A short example screenshot of how the widget admin and meta box in the edit page/post interface will look like at the end of the tutorial:
Step 1 Plugin File Headers
Each WordPress plugin mush have compatible, up to date code in its headers, so that it can function and be recognised by WordPress. This allows it to be installed, activated and removed. The kind of information that is available in the header information is crucial for the plugin but also contains information about it like title, version, description, tags, author info, license, etc.
First, the plugin is a file placed in a directory. We are going to name our plugin Timer Plugin and place it in our wp-content/plugins folder under the directory timer_plugin. Then inside that, the file timer_plugin.php will be our main plugin file where we insert the header source code.
We are just going to use the basic variables needed to get the plugin up and running. One of the variables is the Plugin Name, that is very important in order to identify the plugin in the plugin installation page. For the purposes of this tutorial we are just going to name it Timer Plugin. Next, the Description that is a short line of text describing the plugin. That will also be visible under the plugin installation page right next to the plugin, along with the next variables, the Author and Version.
“All header plugin variables are strings of text written after the : preceding the header variable names.”
Step 2 Adding Actions
In WordPress, actions are hooks to specific functions that you might want to use in your functionality. In this tutorial we are going to use a number of hooks to get the desired result.
First, the actions are going to be added using the add_action function for each action, and we are going to add them at the end of the PHP file as the next example:
Next, in the above example, the wp_print_scripts and wp_print_styles hooks add actions to functions that are used to register and include the styles and scripts needed in the WordPress front end. More precisely in the website theme, for the functionality of the sidebar widget timer and the content shortcode. The admin_print_scripts and admin_print_styles hooks are used to register the WordPress admin panel script and CSS style files used later on in the tutorial.
Finally, the admin_init hook pointing to the function that runs before the headers are generated and run. A hook that we will cover at the end of the tutorial is save_post. This hook is required to work with the post or page submitted information in WordPress admin.
Step 3 Registering and Including Scripts and Styles
For this tutorial we are going to require a number of script and style files that are required for good functionality and look on both the admin and the theme implementation of the Timer Plugin. Here is how we are going to do this:
Including Styles for WordPress Admin Functionality:
The Timer Plugin requires a few elements in the admin panel that we will need to style slightly as the default look is not exactly very welcoming. In order to do this we have called in step 3 the tag hooks that help us do that, now we are going to look at the functions that run when the hooks are called and how they work exactly.
First, the TP_admin_register_styles function for the registered and included admin panel styles.
function TP_admin_register_styles()
Downloading the Styles
Because we are building a countdown timer plugin, we require a specific date and time to countdown to from the present. To do this, amongst other integrations, we are using the wp_register_style function to register the latest custom jQuery UI style so that we may use its design properly in its functionality when generating the sliders and calendar date picker later. The CSS file is generated by downloading the latest jQuery UI from http://jqueryui.com/download selecting Core, Widget, Mouse, Slider, DatePicker from the list of options, jQuery Ui 1.8.20 in the version section, and UI Lightness in the theme dropdown section.
Registering the Styles
There will be a CSS file named jquery-ui-1.8.20.custom.css and an images folder inside the css/jquery-ui folder in the custom generated and downloaded archive that you will get from the previous instructions. We are going to replace the jquery-ui-1.8.20.custom.css file name to jquery-ui.css for a friendlier name and copy it alongside the images folder with all its files in our plugin folder.
After that we can start adding the registration and inclusion functions inside the TP_admin_register_styles function mentioned previously.
The previous example uses wp_register_style to register the jquery-ui.css file by the name of jquery-ui-theme that is later used in the wp_register_style function in the next example. The same approach is used to include the main admin style.css file using this time the name tp-admin-style used in the following examples with the wp_enqueue_style function to include it in WordPress headers properly.
The tp-admin-style is used to register and include the style.css file that will be used for styling the widget and meta-box design that comes by default in the jQuery UI implementation and WordPress default style.
Including Styles for Theme Functionality:
Using the exact same approach as before for registering and including style files we are going to include into the WordPress theme the style files necessary for the design of the widget timer and the shortcode.
function TP_register_styles()
// register
wp_register_style('tp-style', plugins_url('style.css', __FILE__));
// enqueue
wp_enqueue_style('tp-style');
In this case we are including a simple style.css file from our plugin directory that we will include later.
Including Scripts for WordPress Admin Functionality:
Because we are going to build a widget and a meta box with jQuery UI calendar and date time picker functionality, we are going to have to have jQuery, jQuery UI and all the plugins necessary to include and use the slider and datepicker that we will implement later. To do this, we have to make use of the previously written action for the admin_print_scripts hook. The next function will implement the functionality we need.
As we are working inside the WordPress admin panel, we are going to have jQuery and jQuery UI already registered and included in the header, as well as the dependencies and plugins we need: jquery-ui-mouse and jquery-ui-widget. All we are including now is the jquery-ui-core that is not included by default and the datepicker and slider plugins that we need and last, the admin-script.js file that contains all the custom rules for our date-time jquery-ui functionality.
Including Scripts for Theme Functionality:
We need to be able to have inside the front end of the website, a timer that decrements to 0 somewhere in the sidebar as a widget and in the content as a shortcode. As a very easy way to do this, I chose jQuery and some plain javascript to work the timer. As a result we are going to include the script.js file inside the function that registers scripts for the front end hook previously declared.
We are going to also specify jQuery as a dependency as the front end does not have it included by default.
Step 4 Creating the Widget
The plugin is supposed to use a widget as one of the two methods to integrate a timer into the theme, more specifically, the sidebar in this case. To be able to add the timer to the sidebar we need to implement widget functionality for our plugin into WordPress.
Building the Class
To implement widget functionality in the plugin, we must include a widget class named TP_Widget. This name is of course not mandatory but it is mandatory for this class to extend the WP_Widget class in order to inherit its functionality. Therefore we create the class like the next example:
class TP_Widget extends WP_Widget
// the following code will be here
Next comes the code we add inside the class so that we work with the widget the way it’s intended to in WordPress, using all the necessary functions that are required in order to have a functional widget created in WordPress.
First we are going to write the __construct function for the initial required code integration. The __construct function is the place where the widget actually processes. We are going to give the widget a name and description inside this function by inheriting and using the parent’s __construct method like in the following example:
public function __construct()
// widget actual processes
parent::__construct('TP_Widget', 'Timer Widget', array('description' => __('A Timer Plugin Widget', 'text_domain')));
The first parameter is a widget ID, second is a widget name, third an array with the description. The following function is going to be the form function. We are going to build and use this function to set and work with the admin panel widget content form. The next code will run inside the widget placeholder in the admin panel widgets page:
public function form()
if (!$_POST)
$tp_arr = unserialize(get_option('tp_ID_' . $this->number));
else
if ($_POST['tp-hidd'] == 'true')
$tp_arr['tp-title'] = $_POST['tp-title'];
$tp_arr['tp-date'] = $_POST['tp-date'];
$tp_arr['tp-hour'] = $_POST['tp-hour-val'];
$tp_arr['tp-minute'] = $_POST['tp-minute-val'];
update_option('tp_ID_' . $this->number, serialize($tp_arr));
}
// outputs the options form on admin
In this part we have widget information like Title, Date, Hour and Minute. This information is extracted from a serialized array string that is stored into the database by the name tp_ID_X, where X is an unique identifier of the widget, used to identify the data being extracted relative to the widget used.
In this part the widget values are also stored into the array one by one, serialized and stored in the database as an option field for later use.
The next part is the admin widget form elements that are used in the front end.
There are two aspects to look after in this particular section:
First, the tags classes like tp-date, tp-hour, tp-minute that are later worked with in javascript and second, the input fields. Firstly, there is some PHP code inserted in the input fields that exist in the code above, code that is used for storing data either for forms in order to be submitted, or for javascript to be implemented into jQuery and worked with.
At the end of the HTML code above the form function is closed.
Updating the Widget Data
When the widget Save button is pressed in the admin panel, the form information is submitted and processed by the following function:
public function update()
// processes widget options to be saved
if ($_POST['tp-hidd'] == 'true')
$tp_Arr['tp-title'] = $_POST['tp-title'];
$tp_Arr['tp-date'] = $_POST['tp-date'];
$tp_Arr['tp-hour'] = $_POST['tp-hour-val'];
$tp_Arr['tp-minute'] = $_POST['tp-minute-val'];
$tp_Arr['tp-date'] = $_POST['tp-date'];
update_option('tp_ID_' . $this->number, serialize($tp_Arr));
}
The update function is the function used to update the information in the widget in WordPress widgets.
Writing the Widget Output in the Sidebar
This next part is the code that generates and outputs the widget in the sidebar as a widget. Basically it is the contents of the already generated widget code that has the purpose of a compatible wrapper.
Here is an example of just half of the function, namely the PHP code that is used to get the required information for the widget output.
So we are extracting the widget data previously saved in the admin panel. The next part is the HTML and PHP code that represents the timer and/or has the values used later by jQuery to calculate the time and function as a timer.
:0" />
YYDDHHMMSS
-
-
-
-
-
The UL tag is used to create later on a row and column style so that the timer has an ordered look and is given a class in order to easily control the LI tags with jQuery later on.
Also, you may notice the input elements with PHP data in them. Those elements are also used by jQuery to store the values of the saved date and time.
The function is ending after the HTML code with a dynamic variable that closes the widget using WordPress compatible values.
Integrating the Class
Last but not least, if you remember, one of the actions written in step 1 was using the widgets_init tag and pointing to the TP_widgets_init function. We need to write its functionality in order to link the class properly to WordPress.
function TP_widgets_init()
register_widget("TP_Widget");
“For a more extensive look of the standard WordPress widget functionality check out WordPress Widget API”
Step 5 Creating the Meta Box
The meta box is a box located in one of the sidebar panels located in the admin editor of any page or post. Because we are using almost the same HTML, CSS and JavaScript code we are going to use almost the same PHP and HTML code as the widget. Some modifications of some parent element classes are required for jQuery functionality. But first, the meta box must be created and implemented into WordPress from the plugin settings. Another one of the actions written in Step 1 that we did not finish implementing is the admin init hook tag. That hook runs before headers take place and is going to be used by us to implement the meta box functionality with the add_meta_box function like the example below:
function TP_admin_init()
add_meta_box('TP_metaid', __('Timer Plugin Post Settings', 'TP_textdomain'), 'TP_inner_custom_box', 'post', 'side');
add_meta_box('TP_metaid', __('Timer Plugin Page Settings', 'TP_textdomain'), 'TP_inner_custom_box', 'page', 'side');
What this code does is it creates a custom box on the side of each post and page edit page in the admin panel with the content and functionality of the function TP_inner_custom_box. For a more comprehensive view of how add_meta_box should be used, see add_meta_box in WordPress Codex.
Functionality and Front End Code
The meta box has a similar front end with the widget and the back end code is not that different, just slightly different database option field names to save in. Just like the widget admin form it is made out of both PHP and HTML functionality. Starting with the TP_inner_custom_box function we are creating the meta box admin front and back end functionality like the next sample:
function TP_inner_custom_box()
global $post;
// Use nonce for verification
wp_nonce_field(plugin_basename(__FILE__), 'cuschost_noncename');
$tp_arr = unserialize(get_option('tp_pp_ID_' . $post->ID));
After that, the HTML code sample is strikingly similar. The only differences are an extra input button after which, the function is enclosed with the semicolon and ends.
The previous form sends data when the post or page is updated, and we need to get that data and store it for later user. In order to do that we use another hook that we already implemented, mainly the save_post hook tag that points to the callback function TP_save_postdata. The callback function gets the data from post variables and stores it into the database under a post ID unique identifier formed name and it looks like this:
function TP_save_postdata()
global $post;
if ( $_POST['tp-hidd'] == 'true' )
$tp_arr['tp-date'] = $_POST['tp-date'];
$tp_arr['tp-hour'] = $_POST['tp-hour-val'];
$tp_arr['tp-minute'] = $_POST['tp-minute-val'];
update_option( 'tp_pp_ID_' . $post->ID, serialize( $tp_arr ) );
}
Step 6 Implementing the Shortcode
To implement the shortcode we need to add a new action to the add_action function list. The next sample is going to cover it:
add_shortcode('tp-shortcode', 'tp_shortcode');
It goes without saying that we must create the tp_shortcode function that handles the new shortcode.
This stylesheet file handles the width, height, colors and position of the admin widget sliders and calendar jQuery UI popup when choosing hours and minutes from the front-end.
The Timer Front-End Style:
The style.css file is the CSS file that covers the design of the UL, LI, OL of the timer in the front end. See the next sample:
.timer-content width:300px;
.timer-main ul, .timer-content ul float:left; display:inline; overflow:hidden; width:180px; margin:0px; padding:0px; margin-top: 0px; font-weight: bold;
.timer-main ul.tp-head, #content .timer-content ul.tp-head margin:0px; padding:0px; margin-top:20px; font-size:12px;
.timer-main ul ol, .timer-content ul ol float:left; display:inline; overflow:hidden; width:20px; margin:0px; padding:0px; margin-right:2px; text-align: center; border:1px solid #dcdcdc; padding:4px; background:#f0f0f0;
.timer-main ul li, .timer-content ul li float:left; display:inline; overflow:hidden; width:20px; margin:0px; padding:0px; margin-right:2px; text-align: center; padding:4px; border: 1px solid white;
Some elements are floated, resized and positioned with margins so they will look as intended. A result of this style is the design in the next picture:
Step 8 Admin Widget and MetaBox Javascript Code
The admin Widget requires very specific jQuery functionality mixed perfectly with HTML classes for tags. All of the following code should be put inside the admin-script.js file.
In this example, after a jQuery initialization and a document load event all the code that works with the widget and shortcode is loaded for use.
Now, because the widget has ajax-loaded dynamic content in it all its content is invisible to jQuery unless used with a live action. For this purpose, a link with the class name of tp-time-edit and tag option javascript functionality of void(0) was created and when clicked, runs the live hook and makes all HTML tags in the event function call available.
Inside the callback function we are using the functionality needed to create the datepicker for the date textbox by using the tp-date CSS class.
Last but not least, actually at the beginning of the code lies the shortcode javascript functionality, more specifically the jQuery insertion of the tp-insert-shortcode CSS class value found in the input field inside the shortcode function previously written in Step 6. When the button with the class tp-insert-shortcode is pressed, it should add the [tp-schortcode] string value to the WYSIWYG editor.
“Very Important! jQuery UI requires classes in tag properties to be used for the sliders and datepicker plugins. It does not work with ID’s”
Step 9 Timer Javascript Code
This is the most important and slightly most hard to visualise at first sight piece of code in the entire tutorial as it is the part dealing with a lot of math.
This part is referring exclusively to the script.js file that holds the javascript source code dealing with the actual timer both on the widget part and on the shortcode part in the front end.
jQuery(document).ready(function($)
function start_by_parent(tp_parentClass)
var tp_timer ='';
tp_date=$(tp_parentClass+' input.tp-widget-date').val();
tp_time=$(tp_parentClass+' input.tp-widget-time').val();
tp_timer = setInterval("tp_set('"+tp_parentClass+"','"+tp_date+"','"+tp_time+"');", 1000);
start_by_parent('.timer-main');
start_by_parent('.timer-content');
});
The parent class handling the widget is timer-main, as for the shortcode the timer-content CSS class is used as a parent tag element that is used to affect the li tag elements containing the timer values for DD(days), HH(Hours), MM(Minutes) and SS(Seconds). The above implementation is a dynamic approach to both of them in jQuery after the values are sent to the calc_data function to handle all the math.
The tp_set function is actually using the calc_data method to calculate the values before it inserts them in the appropriate HTML tag elements. Here is the implemented tp_set method that needs to go inside the same file, script.js.
Finally, one of the most important parts of this script file, the calc_data method, that calculates the number of seconds between the present and the user selected date and returns the appropriate values so that the timer shows the amount of time left until that date.
function calc_data(tp_date,tp_time)
tempdate = tp_date.split("/");
temptime = tp_time.split(":");
var seconds=1000;
var minutes=seconds*60;
var hours=minutes*60;
var days=hours*24;
var years=days*365;
var db_time = new Date(tempdate[0], tempdate[1]-1, tempdate[2], temptime[0], temptime[1], 00);
var now_time = new Date();
db_time = db_time.getTime();
now_time = now_time.getTime();
var tp_result = db_time-now_time;
if(tp_result < 0)
tp_years=tp_days=tp_hours=tp_minutes=tp_seconds=0;
else
tp_years = Math.floor(tp_result/years);
tp_days = Math.floor(tp_result/days)-(tp_years*365);
tp_hours = Math.floor(tp_result/hours)-(tp_days*24)-(tp_years*365*24);
tp_minutes = Math.floor(tp_result/minutes)-(tp_hours*60)-(tp_days*24*60)-(tp_years*365*24*60);
tp_seconds = Math.floor(tp_result/seconds)-(tp_minutes*60)-(tp_hours*60*60)-(tp_days*60*24*60)-(tp_years*365*24*60*60);
singlebox=false;
if(tp_years > 99)
tp_years=99;
if(tp_days > 99)
singlebox=true;
if(tp_years < 0)tp_years=0;
if(tp_days < 0)tp_days=0;
if(tp_hours < 0)tp_hours=0;
if(tp_minutes > 60)tp_minutes=60;
if(tp_minutes < 0)tp_minutes=0;
if(tp_seconds < 0)tp_seconds=0;
}
}
A very important aspect that needs to be mentioned is that these functions use global variables that were not mentioned yet. It is recommended that you add the following code with global variables at the top of the script.js file before any other code:
Building a countdown timer in jQuery is not exactly a very fast and easy project as there are many aspects that need to be taken into consideration when starting. Things like what javascript classes, plugins and styles will be used, what design it will have in the front and back end, how it stores data and how it pulls it back out. Also the compatibility of all of these with other plugins or scripts and how exactly everything is calculated and what it outputs.
Let us know what you think, and if you have any additional recommendations, in the comments below!
Update: This post has been updated to amend the issues mentioned in the comments.
Update #2: Source files are now available for download at the top of this tutorial.
Original from: http://wp.tutsplus.com/tutorials/plugins/creating-an-ajax-countdown-timer-wordpress-plugin/
Infinite scroll pagination is inspired from Facebook and Twitter. This is just pagination where the user will need to scroll to bottom of the page to read more articles. This is one way to improve the user experience on a website, but if you do it wrong, it can give a bad experience too. If you’re going to implement this type of pagination, make sure you don’t include important links at the bottom of the page. The reason for this is that when a user tries to click on that particular link, the page will auto load new entries and push the link off the screen each time. You can either set a fixed position footer area or make your sidebar visible all the time.
Step 1 Plan Your Pagination
It is important that you plan ahead with your pagination, where you want to include it, and how you are going to process it. A common way of doing pagination is by listing the page numbers at the bottom of the page. Using this method however, no more page numbers will appear at the end of your article list, as they’re no longer needed. This pagination can be use on all themes as long as you don’t include loads of information in your footer section, as it may not give the desired effect.
Our infinite scroll pagination will use jQuery and ajax functionality to make the request and retrieve more articles to be shown to the user. In this tutorial, I will use the Twenty Ten theme as an example, you can view the working demo of the infinite scroll here.
Step 2 Building the Ajax Function
We will use WordPress’ ajax functionality to make the call for this pagination. First we prepare the basic function for our pagination, please insert the following code to your theme’s functions.php
This function will be used to make the call for our pagination, basically we send two variables to this function via ajax, one is the page number and another is the file template we are going to use for our pagination. To enable this function to be used with WordPress ajax, we need the following code.
add_action('wp_ajax_infinite_scroll', 'wp_infinitepaginate'); // for logged in user
add_action('wp_ajax_nopriv_infinite_scroll', 'wp_infinitepaginate'); // if user not logged in
The default action for WordPress ajax would be wp_ajax_(our action name), hence why the name infinite_scroll being used in the code example. We need to add two actions, one for logged in users and another is for users that are not logged in.
Next we will need to build the ajax function that will send the two variables we need for our pagination. You can use WordPress hooks to insert this jQuery ajax function or straight away insert it into your theme header.php
This will be the basic ajax call that we are going to make and we use “infinite_scroll” as our action name. WordPress will automatically call our function wp_infinitepaginate(); because we define it in our theme functions.php previously.
Step 3 Determine When the User Scroll to Bottom of Page
To enable the infinite scroll pagination, we need to determine when the user hits the bottom of the page. This can be achieved easily via jQuery using the following code.
Now we can know when the user hits the bottom of the page. Next we need to call the loadArticle function within the scroll function. I’m adding a counter to be used as the page number of our call.
Each time the user scrolls to bottom of the page, the counter will increase and this will enable us to have the page number pass to our wp_infinitepage() function within our theme’s functions.php. With the scroll and loadArticle functions, we can now do the ajax function call within our WordPress theme, but the result may not appear if we haven’t defined the loop file within our theme folder.
Step 4 Setting Up Our Theme
Most important thing, we need to setup the div that will hold the new content that’s been requested using our ajax function. In the Twenty Ten theme, there is already a div we can use, which is the div with id="content" so we will include the div id in our ajax function. If you use other themes that don’t wrap their loop in a div, you can simply wrap the loop function like the example code below to achieve the same result.
loop content
Next we will need a loop file for this. The Twenty Ten theme already has a loop file included, this is the main reason why I chose Twenty Ten for this example, because it is easier for anyone who wants to reference this later. If you don’t have any loop.php, simply create a new loop file, and copy the loop function within your index.php into the new file and uploaded it into your theme’s folder. For anyone using the Twenty Ten theme, you would want to comment out the pagination included in the file because we won’t need it anymore (please refer to the tutorial source file on how to do this).
Step 5 Adding Ajax Loader
This is optional, just to give a nice touch to our infinite scroll pagination. We will add an ajax loader image as we hit the bottom of the page. You can add the following code to your footer.php
Next we will add a few lines of code to our jQuery function to show and hide this ajax loader element.
The ajax loader will be shown once the user hits the bottom of the page and will be hide once the ajax request has finished.
Step 6 Additional Limitation to Enhance the Infinite Scroll
Up till now, we already have a working infinite scroll, but one thing is missing. The function will keep triggering each time a user hits the bottom page even though there are no more post to be shown. This is something we don’t want to have. We will add a control in our scroll function so when there no more pages to be shown, it will stop.
We add a new var total to the function which will return the total pages available on our site. This will be used to ensure no additional calls will be made to the page if the maximum page has been reached. Another thing we would want to add is a restriction where this function will be loaded. We just want this on our home page, archive or maybe search, but not on our single post and page. So we wrap a simple PHP if else function in our jQuery code.
if (!is_single() || !is_page()):
// our jQuery function here
endif;
That’s pretty much everything you need for the pagination, please refer to the source files for example code used in this tutorial. The files are based on the Twenty Ten theme.
Conclusion
By now you should be able to use this function in any of your theme, if you have any additional suggestions or questions regarding this tutorial, feel free to leave a comment or contact me via twitter. Would love to share any ideas with you guys.
Original from: http://wp.tutsplus.com/tutorials/theme-development/how-to-create-infinite-scroll-pagination/
Programming for speed is not what most coders think of. What they tend to consider first, and usually only, is getting it working. Sometimes people will talk of refactoring to reduce the amount of code, but again this is usually only for those that suffer with the luxury of having too much money and time.
I wish I had that luxury, to be able to spend twice as long on a problem to make a perfect solution. In truth I don’t most of the time, as I am out there getting new clients, making other products or not in the fortunate position to have a client with very deep pockets.
To counteract these things I have a bunch of methods stored in my head that allow me to choose the best path first time (I hope!). I am going to share these best practices with you so you can maybe do the same, maybe even better. If you have any great speed suggestions for coding, please comment and I will append it to this post.
Also, please note that this is not an exhaustive list. This is more of a pointer to things you should consider in your favorite coding language. Although this is for PHP specifically, I’ve tried to keep it as generic as possible to make it possible for all coders, no matter the language, to benefit.
Making IF ELSE smaller
IF is possibly the most used statement from all the programming languages, and I think the most used by a noob programmer (hey I was one once, I remember my code).
As you can see all that has been done is that value is pre-set to ‘no’ and only gets changed to ‘yes’ if something is true. Both bits of code have the same outcome, one has less code.
If you only have 1 command inside the if statement then you can take things a little further. PHP does not require that you have the curly brackets when there is just one line.
We can go a stage further and have Ternary Operators. These are mathematical instructions that allow for a yes/no answer, just like IF.
IF presented as ternary operation
$value = ( $something == true ) ? "yes" : "no" ;
Again the same IF ELSE statement, made much smaller. What it does is check the if the statement inside the brackets is either true or false, if it is true it will set value to be “yes”, if it is false it will set value to be “no”
It is not essential to have an output, as the true or false value could call a function and not return a value.
Using Range to create an array of numbers
Often people will code an array with just a bunch of numbers in it so that they can loop through it.
PHP code to create a select drop down list
// selected item value
$item = 12;
// create array of numbers
$array_of_numbers = array( 2,4,6,8,10,12,14,16 );
// start the select
echo "";
Now the same thing shorter with range
// selected item value
$item = 12;
// start the select
echo "";
Range is a really handy thing, as what it does is created an array of numbers (integers). It has the following syntax in php:
range($start_number, $end_number, $increment);
The only needed compulsory items are the start and end number, the increment defaults to 1, but can be any number you like.
A range function is available in most languages but is unfortunately not available in Javascript out of the box, so to make this same saving in code you would be best to use a FOR loop
FOR loop version
// selected item value
$item = 12;
// start the select
echo "";
Turbo charging the FOR loop
Many people like to use a for loop as they believe that it is faster than a foreach. While this is often true, it does not offer the flexibility of foreach and with the wrong programming techniques can be slower
The slower FOR loop
// some text as a string
$text="We love SpeckyBoy";
// loop through all the characters
for($i=0; $i < strlen($text); $i++)
// look for the o in the text string at the position of $i using a ternary operator
// echo true or false value as needed
echo ( substr($text,$i,1) == 'o' ) ? "its an o" : "no o here";
The faster FOR loop
// some text as a string
$text="We love SpeckyBoy";
// get the length of the string
$length = strlen($text);
// loop through all the characters
for($i=0; $i < $length ; $i++)
// look for the o in the text string at the position of $i using a ternary operator
// echo true or false value as needed
echo ( substr($text,$i,1) == 'o' ) ? "its an o" : "no o here";
The 2nd for loop is faster as it does not need to re-check the string length each time the loop runs. The first loop will check the string length 17 times with the text used
Making your code easier to maintain, and faster
I often see the same problem with my noob code when I re-visit it. The code is all written on 1 line and very long. Check this bit of code as an example:
$html = "";
echo $html;
It works just fine, and will be ok for any implementation, but there are some problems with it. For example if the class is empty, it is wasteful to code the empty class setting. While this may not make so much difference to a Javascript implementation, as this is being generated on the server with PHP, you’d be sending extra bytes to the clients browser which are not required. This of course will make the most difference when making AJAX calls and waiting for the reply, where extra bytes can make much more of an impact.
As you can see, much easier to read, much easier to maintain, and used on the server side will produce less HTML code.
Don’t echo every line only the final output
It’s much easier to echo every line, or pass control back to HTML, than it is to write every line to a variable, yet writing the output to a variable first and only echoing at the end is the faster way to process
The easy way to do things, with a few variations
echo "
" . $title . "
"; ?>
The more server friendly way to do things
$output = "
" . $title . "
";
$output .= "" . date() . "";
echo $output;
OK, this is a very simplistic example of what you should do as it is only 2 lines and then output.
Rounding up
This is a very short list of things to help make your PHP coding faster and easier to maintain. There is of course many more things that you can do to reduce the amount of code that you do use, or the speed that it runs at.
Most of these techniques can be taken across to other programming languages, so when your coding in Javascript or .NET give it some thought and you will be making things much faster.
Recent Comments