Arranging the pages in a menu in order is a no big deal in WordPress. Simply edit the ‘order’ value in the ‘page attributes’ metabox of the pages.
Ordering the posts on a blog page? Well, those appear in order already. Posts appear by the date of publishing.
Now, I may want more control with the ordering of the posts. I wished there was an ‘order’ field for each of the posts, where I could simply alter the value for each post to tailor their order of appearance.
After doing some investigation, I found that such an option is already there. Here is where the things started to get interesting.
Note: All the code mentioned here can be appended to the functions.php.
First of all, we need to tell the system that we need the ‘Page Attributes’ metabox to show up for the posts as well.
[code]
add_post_type_support( ‘post’, ‘page-attributes’ );
[/code]
What this does is, show up the ‘Attributes’ metabox on your post’s edit page. You may need to turn it on from the “Screen Options” if it does not show up by default. You can find the Screen Options tab at the top right of the Edit Post page.
This metabox already has the ‘order’ field in place. This field is actually supposed to contain the menu order for the pages. But, when it shows up for the posts, we can put it to better use. This order will be used to display the position of the posts on the blog.
Let’s create a callback function for ‘pre_get_posts’ action
[code]
add_action( ‘pre_get_posts’, ‘create_new_posts_order’ );
function create_new_posts_order( $query ) {
if ( $query->is_main_query() )
$query->set( ‘orderby’, ‘menu_order’ );
}
[/code]
In the above code, first our callback function i.e., ‘create_new_posts_order’ is registered for the action ‘pre_get_posts’. And then, we define the function itself.
This function sets the ‘orderby’ parameter to use the menu order value specified for each of the posts.
Thats all! Now you can edit the order value for each of the posts in the post edit screen or even in the quick edit form.
After all this effort, the posts will definitely show up on your blog as ordered.
3 Comments