代码之家  ›  专栏  ›  技术社区  ›  ReynierPM

获取Wordpress中所有已发布的帖子,由于结果集过长而导致的性能问题

  •  0
  • ReynierPM  · 技术社区  · 11 年前

    我需要构建一个这样的阵列:

    $arrPosts = array(
        thePostID => "The Post Title"
    )
    

    我的做法如下:

    $posts = get_posts(
        array(
            'numberposts' => -1,
            'post_status' => 'published',
            //'post_type' => get_post_types('post', 'opinion')
        )
    );
    
    foreach($posts as $post) {
        $article[] = [
            $post->ID => $post->title
        ];
    }
    

    但需要很长时间来处理,这是不合适的(我必须设置 define('WP_MAX_MEMORY_LIMIT','1024M') 这是大量存储器)。我只需要从帖子和意见自定义帖子类型中获取帖子。

    有人知道实现这一目标的更好方法吗?

    1 回复  |  直到 11 年前
        1
  •  2
  •   Vidya L    11 年前

    您可以使用 wp_query() 这样地,

    $args = array(
                  'post_type' => 'post',
                  'orderby'   => 'title',
                  'order'     => 'ASC',
                  'post_status' => 'publish', //here you can retrieve posts that are published
                  'posts_per_page' => -1,
                );
    
    // The Query
    $the_query = new WP_Query( $args );
    $posts = array();
    // The Loop
    if ( $the_query->have_posts() ) {
        while ( $the_query->have_posts() ) {
            $the_query->the_post();
            $posts['thePostID '] =  get_the_title() ; //change appropiately
        }
    
    } else {
        // no posts found
    }
    print_r($posts);
    /* Restore original Post Data */
    wp_reset_postdata();