1

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.

1
  • If you never want to show books that are not passed their release date, then why not just plan the posts instead? the fields will essentially be the same? Commented Oct 2, 2017 at 12:16

2 Answers 2

1

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() ) {
        $your_query->the_post();
        var_dump($post)
    }
}

More info here

Sign up to request clarification or add additional context in comments.

Comments

0

So if u want only post where release-date is bigger than today you can do an easy wp-query to get all post:

function getPostsByQuery(WP_Query $query)
{
$posts = array();
if ($query->have_posts()) {
    while ($query->have_posts()) {
        $query->the_post();
        $posts[] = $query->post;
    }
    wp_reset_postdata();
}

return $posts;
}

function getPostsByCustomemField($name, $limit = -1)
{
    return getPostsByQuery(new WP_Query(array('post_type'=>'books','meta_key' => $name, 'posts_per_page' => $limit)));
}

function getBooks() {
    $posts = getPostsByCustomemField('release-date');
    $books = [];
    foreach ($posts as $post) {
    if (get_post_meta($post->ID,'release-date',true) > date('d/m/Y',strtotime("today"))) {
        $books[] = $post;
    }
}
    return $books;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.