aletede91 aletede91 - 3 years ago 189
PHP Question

Using query_posts with custom fields

I have a custom post type called "books".

This post type has a custom field called "release-date" that contains a unix timestamp.

I'm working on WordPress archive.php page to have a list of books and I'm trying to alterate the main query.

What I need is to have only books with release-date > today and sorted by release-date.

This is what I try to sort it:

global $query_string;
query_posts( $query_string . "&meta_key=release-date&orderby=meta_value_num&order=ASC&posts_per_page=9" );

The sorting seems not working as expected.

Answer Source

I think that by now you should use the WP_Query class:

$args = array(
    'post_type' => 'books',
    'meta_query' => array (
        'key' => 'release-date',
        'value' => date('d/m/Y',strtotime("today")),
        'type' => 'DATE',
        'compare' => '>='
    'meta_key' => 'release-date',
    'orderby' => 'meta_value_num',
    'order' => 'DESC'

and then, just

$your_query = new WP_Query( $args );
if ($your_query->have_posts()) {
    while ( $jobs_query->have_posts() ) {

More info here

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download