Dev Notes

Various Cheat Sheets and Resources by David Egan/Carawebs.

An Array of Post IDs from WP_Query


PHP, WordPress
David Egan

Return an array of Post IDs from a WordPress WP_Query object - which can then be used to set up data from the _postmeta table.

By having the query only return IDs, it is quicker and more efficient - but I constantly forget how to set it up.

Note: There’s no loop to set up, you get the array from the object’s posts property: $query_object->posts.

WP_Query

/**
 * Return an array of post IDs
 *
 * Build a more efficient query by only returning an array of post IDs.
 *
 * @author David Egan
 * @return array Array of post IDs
 * @see http://codex.wordpress.org/Class_Reference/WP_Query#Return_Fields_Parameter
 */
function carawebs_student_questionnaire_results(){

  $args = array(
    'post_type'     => 'questionnaire-result',
    'post_status'   => 'publish',
    'fields'        => 'ids',
    'meta_query'    => array(
      array(
        'key'        => 'user_type',
        'value'      => 'student',
        'compare'    => '=',
        'type'       => 'CHAR',
      ),
    ),
  );

  // The Query
  $result_query = new WP_Query( $args );

  $ID_array = $result_query->posts;

  // Restore original Post Data
  wp_reset_postdata();

  return $ID_array;

}

Resources


comments powered by Disqus