Created
September 17, 2018 03:12
-
-
Save psorensen/95be28c319b427d514e7fad4bdbaaed3 to your computer and use it in GitHub Desktop.
WP Paginated Query
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
use WP_CLI; | |
/** | |
* Paginated Query that performs callback for each iteration. | |
* | |
* @param string $callback Name of the callback function. | |
* @param array $args WP_Query arguments. | |
* @param string $message Message passed to WP CLI make_progress_bar. | |
* | |
* @throws \Exception Throws if function empty or not callable. | |
*/ | |
function wp_paginated_query( $callback = '', $args = [], $message = 'Paginating through posts' ) { | |
if ( empty( $callback ) || ! is_callable( $callback ) ) { | |
wp_cli::error( 'Paginated Query: No valid callback function provided.' ); | |
} | |
$offset = 0; | |
$defaults = array( | |
'posts_per_page' => 50, | |
'post_type' => 'any', | |
'post_status' => 'any', | |
); | |
$args = wp_parse_args( $args, $defaults ); | |
$query = new \WP_Query( $args ); | |
$progress = WP_CLI\Utils\make_progress_bar( esc_html( $message ), $query->found_posts, 10 ); | |
while ( true ) { | |
// Update this iteration's offset. | |
$args['offset'] = $offset; | |
// Run the query. | |
$query->query( $args ); | |
if ( $query->have_posts() ) { | |
while ( $query->have_posts() ) { | |
$query->the_post(); | |
call_user_func( $callback, get_post() ); | |
$progress->tick(); | |
} | |
} else { | |
break; | |
} | |
// set offset for next page. | |
$offset += $args['posts_per_page']; | |
// Take a breath. | |
usleep( 500 ); | |
} | |
$progress->finish(); | |
wp_reset_postdata(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment