• Resolved vovazuev

    (@vovazuev)


    Hi!
    I have a custom post type with several meta fields. I need to output the posts on the page ordered by a meta value. Here is my query:

    <?php $query = new WP_Query(array(
    	'post_type' => 'message',
    	'posts_per_page' => 5,
    	'meta_key' => 'date',
    	'orderby' => 'meta_value_num'
    )); ?>

    The meta_key ‘date’ is actually present in the wp_postmeta table. This date is a custom field and is unrelated with the date of publication.

    But that query outputs 0 posts. None of the other meta keys also work. When I pass empty meta_key the query outputs the posts ordered by default.

    What may be the problem here? Thanks!

    • This topic was modified 5 years, 7 months ago by vovazuev.
Viewing 2 replies - 1 through 2 (of 2 total)
  • Hi vovazuev,

    Can you try with below code?

    <?php $query = new WP_Query(array(
    	'post_type' => 'message',
    	'posts_per_page' => 5,
    	'orderby' => array(
    	   'meta_value_num' => 'ASC'
    	  ), 
    	 'meta_query' => array(
    	   array(
    		 'key' => 'date',
    		 'compare' => 'EXISTS',
    	  ),
       ),
    )); 
    ?>

    Hopefully, it will work.

    Thread Starter vovazuev

    (@vovazuev)

    Thanks, Minerva Infotech!

    I found the problem. The metadata of actual posts had been wrapped in an array. As soon as I got rid of that, everything worked.

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Custom query meta_value not working’ is closed to new replies.