Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I made a mysql query to WordPress like this:

$querystr = "
    SELECT $wpdb->posts.*
    FROM $wpdb->posts, $wpdb->postmeta
    WHERE $wpdb->posts.ID = $wpdb->postmeta.post_id
    AND $wpdb->postmeta.meta_key = 'where'
    AND $wpdb->postmeta.meta_value = 'london'
    LIMIT 0,50  ";

$pageposts = $wpdb->get_results($querystr, OBJECT);

In this way i can grab all posts with meta_key = "where" and meta_value = london

The problem is that I've also got another meta_key, "date" and a meta_value that contains the real date like "05-06-2013", "06-06-2013", etc.

How can I query all posts with meta "where" = "london" and order by date using the data contain in meta "date" = "xx-xx-xxxx" ?

share|improve this question

1 Answer 1

While the WPDB class, or its global $wpdb instance are your friend when it comes to querying custom tables or WP core data that does not have a higher-level API, it is overkill to use it to query posts.

Instead, read up on WP_Query.

In your case, you'd use it like so:

$args = array(
    'posts_per_page' => 50,    /* set limit to 50 */
    'post_type' => array( 'post', 'page' ), /* fetch both posts and pages */
    'meta_key' => 'date',    /* garb only posts with meta_key "date" set */
    'orderby' => 'meta_value_num',    /* sort by numeric value of above key */
    'order' => 'ASC', /* sot order */
    'meta_query' => array(    /* grab only posts/pages w/ "london" as value for "where" */
        array(
            'key' => 'where',
            'value' => 'london',
            'compare' => '='
        )
    )
);

$pageposts = new WP_Query( $args );

while ( $pageposts->have_posts() ) :
    $pageposts->the_post();
    /* output something */
endwhile;

wp_reset_postdata();

The above sorting by date will work flawlessly with either a timestamp or a YYYY-MM-DD string format.

With the way you currently have it, you will need an additional iteration...

share|improve this answer
    
There are some differences between the MySQL query in the question and your solution. At first, the MySQL query limits the number of results to 50. -1 will return all results. And second, the MySQL query return all kind of posts (publish, trashed, draft, etc). Your solution returns only published posts/pages. –  Ralf912 May 5 '13 at 12:14
    
Set the limit to 50 now, obviously did not see that. But, @Ralf912, the latter point I assumed to be unwanted in the first place, given that the OP chose to call his variable holding the query results $pageposts... –  Johannes Pille May 5 '13 at 12:23

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.