How to display custom post type ordered by a custom field date

I have a custom post type for a timeline activities.

each post of them has a custom field type of DATE. field name :activity-date

I'm using TYPES plugin for Custom Post Type and Custom Fields

I would like to order these posts by the custom date field, I tried the following but didn't work.

?php $activities = new WP_Query( array(
    'post_type' = 'timeline',
    'posts_per_page' = -1,
    'key'           = 'activity-date',
    'orderby'       = 'meta_value_num',
    'order'         = 'ASC'                            
)); ?

Topic date order custom-field custom-post-types Wordpress

Category Web


After a long search, it appeared that TYPES plugin is storing the meta_key's name like

'meta_key' => 'wpcf-yourmetakey'

The solution is :

<?php $activities = new WP_Query( array(
    'post_type'         =>  'timeline',
    'posts_per_page'    =>  -1, 
    'meta_key'          => 'wpcf-activity-date',
    'orderby'           => 'meta_value',
    'order'             => 'DESC'
    ));
?>

The correct array key to use is meta_key, not key. You can only use key as part of a meta_query subarray, where the 'meta' part is implied.

This is all described in the codex.

Try

<?php $activities = new WP_Query( array(
    'post_type' => 'timeline',
    'posts_per_page' => -1,
    'meta_key'      => 'activity-date',
    'orderby'       => 'meta_value_num',
    'order'         => 'ASC'                            
)); ?>

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.