从WooCommerce商店获取所有产品

时间:2014-10-14 16:40:02

标签: php wordpress woocommerce wp-query

我想在我的Woocommerce网上商店中获取所有产品。我想获取所有产品的这些数据,并将其打印为json。但该页面一直显示为空白。

尝试使用以下内容获取所有产品ID,以便显示所有产品。

$args = array( 'post_type' => 'product', 'post_status' => 'publish', 'p' => '*');

我也试过这个:

    $args = array( 'post_type' => 'product', 'post_status' => 'publish', 'posts_per_page' => 470);

   $loop = new WP_Query( $args );

而且:

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

   $loop = new WP_Query( $args );

所有产生相同的结果,页面显示为空白,没有数据。

之前我使用过类似的代码,例如显示特定类别中的所有产品并且它有效。但我似乎无法让这个工作,以显示商店中的所有产品。

请帮忙吗?

2 个答案:

答案 0 :(得分:2)

WooCommerce 2.1+现在附带了它自己的REST API。你一定要看一下。 请注意,您必须使用https或OAuth来访问它,因此您可能希望使用像one这样的客户端(我与此库无关)。

目前尚不清楚您要从商店中检索哪些数据,但是从上面的设置中,您可以尝试这个简单的演示示例:

add_action( 'init', function() {
    add_rewrite_endpoint( 'wooexport', EP_ROOT );
});

add_action( 'template_redirect', function() {
    if( 'json' === get_query_var( 'wooexport' ) ) {
        $posts = get_posts( array( 'post_type' => 'product' ) ); 
        wp_send_json_success( $posts );
    }  
});

您必须记住刷新重写规则,例如重新保存永久链接设置。然后,您可以根据需要修改查询参数,并从example.com/wooexport/json/访问它。

很可能你有一个PHP语法错误,导致白屏?因此,请始终在测试网站上使用WP_DEBUG,例如从Codex查看Debugging in WordPress

答案 1 :(得分:0)

我建议您使用wordpress中的导出选项从当前站点获取数据,然后使用导入选项在您想要的新站点中获取数据。这很简单,根本不需要编码。

相关问题