Get WordPress posts incremently to save on PHP memory usage
// memory friendly alternative to get_posts( array( 'posts_per_page' => '-1' ) ); | |
$product_page = 1; | |
$product_per_page = 10; | |
$product_query = new WP_Query( array( | |
'posts_per_page' => $product_per_page, | |
'paged' => $product_page, | |
'post_type' => array( 'product', 'product_variation' ), | |
) ); | |
$product_ids = array(); | |
while($product_query->have_posts() ) { | |
$product_result = $product_query->next_post(); | |
if(!$product_result){ | |
// get the next lot of results. | |
$product_page++; | |
$product_query = new WP_Query( array( | |
'posts_per_page' => $product_per_page, | |
'paged' => $product_page, | |
'post_type' => array( 'product', 'product_variation' ), | |
) ); | |
}else{ | |
$product_ids[] = $product_result->ID; | |
} | |
} | |
print_r($product_ids); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment