How to order a custom WordPress Post Type by a custom numeric field How to order a custom WordPress Post Type by a custom numeric field

How to order a custom WordPress Post Type by a custom numeric field

So, you need to order a custom WordPress Post Type by a custom numeric field – how?

The Problem

You have a WordPress custom post types, and you need to order by a custom numeric field – how do you do that?

The Cause

You would think that it would be relatively simple, for example the below should work

<?php $loop = new WP_Query( array( 'post_type' => 'staff-member',
'posts_per_page' => 100, 'order' => 'ASC', 'orderby'	=>
'meta_value', 'meta_key' 	=> 'OrderByField','type' => 'numeric' ) ); ?>

But ‘OrderByField’ is treated as a text field, and the number 10, comes after 1, not 2.

The Solution

Use the magic keyword meta_value_num, so your WP_Query would look like this

<?php $loop = new WP_Query( array( 'post_type' => 'staff-member',
'posts_per_page' => 100, 'order' => 'ASC', 'orderby'	=>
'meta_value_num', 'meta_key' => 'StaffOrderBy',
'type' => 'numeric' ) ); ?>
the _num makes all the difference - WordPress will treat it as a numeric field.

 

Written By Steve French

 

One response to “How to order a custom WordPress Post Type by a custom numeric field”

  1. Nice. I’m attempting to do something similar. I want my posts to be ordered alphabetically via values from a custom text field. Not sure how to do it, though. Any thoughts?

Leave a Reply

Your email address will not be published. Required fields are marked *






Copyright 2011 Digital Tool Factory. All Rights Reserved. Powered by raw technical talent. And in this case, WordPress.