在自己的插件中获取所有 WooCommerce 产品

Get all WooCommerce products within own plugin

在插件中如何使用 wc_get_products() 获取产品?或者有其他方法吗?

if ( in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) ) {
      // Put your plugin code here
      add_action( 'woocommerce_loaded', 'generate_product_qr_codes');
}
function generate_product_qr_codes {
$args = array(
    'post_status' => 'publish',
    'limit' => 100
  );
  $products = wc_get_products( $args );
}

问题是没有返回产品(空数组)。

试试这个

if ( in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) ) {
        // Put your plugin code here
        add_action( 'woocommerce_loaded', 'generate_product_qr_codes' );
    }
    
    function generate_product_qr_codes() {
    
        $args        = array( 'post_type' => 'product', 'posts_per_page' => -1 );
        $products    = get_posts( $args );
        echo '<pre>$products:-';
        print_r( $products );
        echo '</pre>';
    }