Woocommerce: get a list for all sku product

2019-07-11 14:16发布

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

2条回答
forever°为你锁心
2楼-- · 2019-07-11 14:47

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!

查看更多
闹够了就滚
3楼-- · 2019-07-11 14:58

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').

查看更多
登录 后发表回答