2

I would to get in a <li> list all sku there are in an ecommerce. I belive that I should use foreach cycle, but I don't know how to recall the selection of all products.

Thanks for all reply, and sorry for my bad english. Greatings

user3324080
  • 25
  • 1
  • 4

2 Answers2

8

Never, ever use query_posts. It is only for the main query loop and should never be modified. There are many, many other ways of grabbing the posts you want. For example:

$args = array(
    'post_type' => 'product', 
    'posts_per_page' => -1
);

$wcProductsArray = get_posts($args);

if (count($wcProductsArray)) {
    foreach ($wcProductsArray as $productPost) {
        $productSKU = get_post_meta($productPost->ID, '_sku', true);
        $productTitle = get_the_title($productPost->ID);

        echo '<li>' . $productSKU . '</li>';
    }
}

It's worth noting that this method will only fetch simple products, and will not include product variations. If you want to grab those too, you'll need to update the $args to 'post_type' => array('product', 'product_variation').

Community
  • 1
  • 1
indextwo
  • 5,535
  • 5
  • 48
  • 63
1

Please try this. Let me know if this works perfectly ;)

$args = array( 'post_type' => 'product', 'posts_per_page' => -1 );
query_posts( $args );
if( have_posts() ):
    echo '<ul>';
    while ( have_posts() ) : the_post();
        echo '<li>'. $product->get_sku() . '</li>';
    endwhile;
    echo '</ul>';
endif;

Cheers!

  • Thanks, it works. But another questions, if I would put this code in a widget, the code remains the same, or should be changed? I tried to put the code in a widget preset but wordpress give me an error. Thanks again for the help. – user3324080 Feb 18 '14 at 17:38
  • 1
    You're missing a line to assign $product, probably: $product = wc_get_product($post->ID) – RichardAtHome Oct 05 '15 at 15:47
  • 1
    As @RichardAtHome mentioned, you're not declaring `$product`; you need to grab the WC product object before you can run any methods against it. But more importantly: **Never, ever use query_posts.** It is only for the main query loop and should never be modified. There are many, many other ways of grabbing the posts you want. For reference: http://wordpress.stackexchange.com/a/1755/17826 – indextwo Jul 07 '16 at 12:32