示例#1
0
文件: posts.php 项目: r-a-stone/wplib
 /**
  * Query the posts.  Equivalent to creating a new WP_Query which both instantiates and queries the DB.
  *
  * @param array $args
  * @return WP_Post[]
  *
  * @todo https://github.com/wplib/wplib/issues/3
  * @see https://github.com/wplib/wplib/commit/8dc27c368e84f7ba6e1448753e1b1f082a60ac6d#commitcomment-11026403
  */
 static function get_query($args = array())
 {
     if ($args instanceof WP_Query) {
         $query = $args;
     } else {
         if (isset($args['post_type']) && WPLib_Post::POST_TYPE == $args['post_type']) {
             if (!isset($args['order'])) {
                 $args['order'] = 'DESC';
             }
             if (!isset($args['orderby'])) {
                 $args['orderby'] = 'ID';
             }
         }
         $args = wp_parse_args($args, array('post_type' => 'any', 'post_status' => 'publish', 'posts_per_page' => WPLib::max_posts_per_page(), 'index_by' => false, 'orderby' => 'menu_order', 'order' => 'ASC', 'no_found_rows' => true));
         if (!empty($args['post__not_in']) && !is_array($args['post__not_in'])) {
             $args['post__not_in'] = array($args['post__not_in']);
         }
         $query = new WPLib_Query($args);
         if ($args['index_by'] && preg_match('#^(post_(id|name)|id|name)$#', $args['index_by'], $match)) {
             $index_field = 'id' == $match[1] ? 'ID' : 'post_name';
             $posts = array();
             foreach ($query->posts as $post) {
                 $posts[$post->{$index_field}] = $post;
             }
             $query->posts = $posts;
         }
     }
     return $query;
 }