0

I am doing the following to get all the children associated with a post:

    $args = array(
        'order'=> 'ASC',
        'post_parent' => get_the_ID(),
        'post_status' => 'publish',
        'post_type' => 'task'
    );
    $tasks = get_children( $args );

Now the posts of type task have postmeta associated with them. One particular meta_key is task_progress. I would like to get all the children whose task_progress meta_value is less than 100. What is the best way to filter the results?

1 Answer 1

0

This should do the trick:

global $wpdb;
$parent = 1; // Make sure it's int (intval() it) as it's not escaped in the query
$posts = $wpdb->get_results(
    "SELECT `post_id` AS `ID`, `meta_value` AS `Progress` FROM {$wpdb->postmeta}
        WHERE `meta_key`='task_progress' AND `meta_value` < 100 AND `ID` IN
            (SELECT `post_id` FROM {$wpdb->posts} WHERE `post_parent`={$parent})
        ORDER BY `meta_value` DESC, `post_id` DESC;" // Sort descending
);
foreach($posts as $post){
    $progress = $post->Progress;
    $post = get_post($ID = $post->ID);
    // Print here
}

Regards.

2
  • Is there a way to do this without a direct query?
    – v0idless
    Commented Oct 22, 2011 at 3:17
  • 2
    Not sure and, if it were, there's too much overhead in the parametrized WP queries. This returns just IDs and Progress. Light data, kind on resources. Usually WP returns Post Objects, very inefficient. Commented Oct 22, 2011 at 3:26

Your Answer

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

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