To fetch all products from the database using WP_Query, you need to follow these steps:
- First, define your query arguments. To get all published products without pagination, use this:
$args = array( 'post_type' => 'product', 'post_status' => 'publish', 'posts_per_page' => -1 );
- Next, create a new instance of WP_Query and pass in your query arguments:
$query = new WP_Query( $args );
- Finally, you can loop through the results and operate on each product:
if ( $query->have_posts() ) {
while ( $query->have_posts() ) {
$query->the_post();
global $product;
// Operate on the $product variable here.
}
wp_reset_postdata();
}
Leave a Reply