WordPress.org

Ready to get started?Download WordPress

Forums

Query multiple custom fields (5 posts)

  1. Sarnix
    Member
    Posted 2 years ago #

    Hi!

    I want to get all posts from 1 category and then sort them ascending by date, then by time and then by location. Is that possible and how does one do it?

    So far I find only solutions where you can sort by 1 meta_key. Like in this example:

    $args = array("category_name" => "program", "order" => "ASC", "orderby" => "meta_value", "meta_key" => "event_date");
    $query =  new WP_Query($args);
  2. Sarnix
    Member
    Posted 2 years ago #

    The question wasn't very clear. So I'll try it again.

    In 1 template I want to show all posts of the category program. A post contains besides the usual fields some custom values: event_date, event_time, location and 2 or 3 more.
    I want to display the posts ordered by event_date, event_time and then by location.

    What function or sql statement do I need to use in order to get an array of posts in that specific order?

  3. esmi
    Forum Moderator
    Posted 2 years ago #

  4. Sarnix
    Member
    Posted 2 years ago #

    Yes, I read those pages and I found so many other pages on how to search a post on meta_keys. But I can't figure out how to retrieve all posts from a single category already containing all custom values so I can sort them before I loop through in the template.

  5. Sarnix
    Member
    Posted 2 years ago #

    I got it (allthough i can probably leave out the joins). I still would like to know how to put the values into the array, but this is the query:

    SELECT DISTINCT wposts.*
            FROM $wpdb->posts wposts
            JOIN $wpdb->postmeta wpostmeta ON wpostmeta.post_id = wposts.ID
            JOIN $wpdb->postmeta wpostmeta2 ON wpostmeta2.post_id = wposts.ID
            JOIN $wpdb->postmeta wpostmeta3 ON wpostmeta3.post_id = wposts.ID
            WHERE wposts.ID = wpostmeta.post_id
            AND wposts.ID = wpostmeta2.post_id
            AND wposts.ID = wpostmeta3.post_id
            AND wpostmeta.meta_key = 'event_date'
            AND wpostmeta2.meta_key = 'event_time'
            AND wpostmeta3.meta_key = 'location'
            ORDER BY wpostmeta.meta_value ASC, wpostmeta2.meta_value ASC, wpostmeta3.meta_value ASC'

Topic Closed

This topic has been closed to new replies.

About this Topic