Change the custom posts order in WordPress

The fact that WordPress was not born as CMS still reveals itself on a regular basis. An example of this is when we want to show, with an order defined by us, a number of elements belonging to a custom post type, which, in turn, belong to a custom taxonomy (in a URL like /<taxonomy-name>/<taxonomy- term>). By default they are shown in order of creation.

This implies creating a new instance of WP_Query with all the arguments needed to get what we want.

Creating an array with the arguments is not that simple. Mainly because it’s necessary to know what arguments are, what we need, which we can ignore, etc. The simplest way to create this array is to use the work that WordPress already has done.

Just get the original query array and join it with only the arguments we to change. In this example, orderby and order. We do this with the PHP function array_merge, which concatenates a number of arrays always using the values of the last array in case of conflict (exactly what we want).


// get the global variable
global $wp_query;

// merge our values in the original array
$args = array_merge(
    ['orderby' => 'menu_order', 'order' => 'ASC']

// new query with the new arguments
$query = new WP_Query($args);


Quick and easy.

Related tip: Alternatively to set the order individually in each post editing page it’s best to use a plugin like Simple Page Ordering.