Sort posts by custom fields

Each post has a posted date and “resource field” where i have another field with date (not the same with posted date). Can someone tell me how can I access… resource-field date?. I have posts and i need to sort them by “resource-field”->date desc for each one category.

This is the query but doesn’t work…

<?php $terms = get_terms( 'resources-categories', array('hide_empty' => false)); ?>
<?php foreach( $terms as $term ): ?>
<ul>
<?php
$query = new WP_Query( array(
            'post_type' => 'resources',
            'resources-categories' => $term->slug,
            'posts_per_page' => '-1',
            'meta_key' => 'date',
            'meta_value' => date('F Y'),
            'meta_compare' => '>',
            'orderby' => 'meta_key',
            'order' => 'DESC',
            'post_parent' => 0) 
            );
if ($query->have_posts()) : $count = 0;
while($query->have_posts()) :
$query->the_post(); ?>
<li> 
//print code...
</li>
<?php endwhile; endif; ?>

Related posts

Leave a Reply

1 comment

  1. I tend to have better luck using the meta_query property of the $args array. Here’s your example restructured using this property:

    $today = date('Y-m-d');
    $args = array(
        'post_type' => 'resources',
        'posts_per_page' => '-1',
        'meta_key' => 'date',
        'meta_query' => array(
            array(
                'key' => 'date',
                'value' => $today,
                'type' => 'date',
                'compare' => '>'
            )
        ),
        'orderby' => 'meta_value_num',
        'order' => 'DESC',
        'post_parent' => 0
    );
    

    A couple of notes:

    • Notice that I have changed your date format. Your original format was going to use the textual representation of the month. WordPress isn’t going to be able to “compare” that value as it’s represented as a string. I’m making an assumption that your date is being stored in a standard SQL format of yyyy-mm-dd. But this could be a significant roadblock for you. You just need to be sure you can know what the actual format of the date is (as it’s stored in the database) and then match that format in the $today variable.

    • Notice that I’ve included the meta_key value. It looks redundant, but it’s not. It’s required for sorting to work.

    • Finally, you included a property named 'resources-categories' => $term->slug, but this will not have any effect on the query. (So I removed it). If you need to additionally query against a taxonomy, you’ll want to look at the tax_query property of the $args array.

    Hope this helps a bit, have fun!