高效地循环访问大量帖子

时间:2012-12-16 作者:Howard

我想循环所有帖子进行一些处理,但我担心的是有很多帖子,这可能会耗尽我的内存,所以我想循环帖子offset, 类似于paging.

e、 g。

$posts = get_posts(array(\'post_status\' => \'publish\', \'posts_per_page\' => -1));

foreach ($posts as $post) {
  // Huge memory requirement as $posts might be huge
}
有什么推荐的方法吗?

1 个回复
SO网友:Ralf912

调用外部脚本:函数如下所示:

<?php    
function modify_posts() {
    $number_posts = 10;
    $offset = 0;
    $success = \'success\';

    while ( \'success\' === $success ) {

        $url = add_query_arg(
                array(
                    \'num\' => $number_posts,
                    \'off\' => $offset,
                    \'abs\' => urlencode( ABSPATH )
                    ),

                    plugins_url( \'remote_get.php\', __FILE__ )

        );

        $response = wp_remote_get( $url );

        if ( ! is_wp_error( $response ) ) {

            $success = json_decode( $response[\'body\'] );

            if ( \'success\' != $success ) {
                // something went wrong in remote_get.php
            }

        } else {
            // wp_remote_get() throws an error...
        }

        $offset += $number_posts;

        printf( "%d -> %s<br>", $offset, $success );

    }

}

remote_get.php

<?php
$offset = filter_input( INPUT_GET, \'off\', FILTER_SANITIZE_NUMBER_INT );
$number_posts = filter_input( INPUT_GET, \'num\', FILTER_SANITIZE_NUMBER_INT );
$abspath = urldecode( filter_input( INPUT_GET, \'abs\', FILTER_SANITIZE_URL ) );

require_once $abspath . \'wp-load.php\';

$posts = get_posts(
        array(
                \'post_status\' => \'publish\',
                \'posts_per_page\' => $number_posts,
                \'offset\' => $offset
                )
        );


if ( ! empty( $posts ) ) {

    foreach ( $posts as $post ) {

        // do wired things here

        $result = \'success\';

    }

} else {

    $result = \'posts_ended\';

}

header( \'Content-Type: application/json\' );

die( json_encode( $result ) );

结束