get_posts only getting most recent product

I had a website built on Woocommerce for me, but no longer have access to the Developer. I'm not a programmer so anything beyond CSS changes gives me quite a bit of problems. There is a piece of code that was working fine, but I have added an additional item to the site and now it only will fetch the most recent item added. I believe the problem is that get_posts is only collecting the latest product and I need it to collect all of them. Pretty sure I've narrowed it down to these two lines:

$products = get_posts(array('post_type' = 'product'));

$product = wc_get_product($products[0]-ID);

Does this need a loop? Sorry, I'm really not equipped to deal with this and it's really hard to find someone who can help me with a single question like this.

Topic woocommerce-offtopic get-posts Wordpress

Category Web


I probably asked my question poorly, but I did figure out the answer with help from a friend. I did need to create a loop. The problem was that I was calling all the post_type products, but then I was asking for just the latest one. Simple enough to add a loop statement and good to go.

$products = get_posts(array('post_type' => 'product'));
foreach($products as $product) {
$product = wc_get_product($product->ID);

In order to get all product you need to specify the option post_per_page and make it -1. You also need a loop if you want fetch all the products data.

You can try this code :

$products = new WP_Query(array('post_type' => 'product', 'posts_per_page' => -1));

    while ($products->have_posts()) : $products->the_post();
        $id = get_the_ID();
        $product = new WC_Product($id);
        //your remaining code to get all product info
    endwhile; 

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.