下面的代码是用来获取在我的Wordpress网站上使用Woocommerce的“图书”类别的产品的数据。
<?php
$args = array( 'post_type' => 'product', 'posts_per_page' => 200, 'product_cat' => 'books');
$loop = new WP_Query( $args );
$send_array = array();
while ( $loop->have_posts() ) : $loop->the_post();
global $product;
$send_array[] = array(
'id' => get_the_ID(),
'title' => get_the_title(),
'content' => get_the_content(),
'regular_price' => get_post_meta( get_the_ID(), '_regular_price', true),
'sale_price'=> get_post_meta( get_the_ID(), '_sale_price', true),
'weight' => woocommerce_get_product_terms($product->id, 'weight', 'names')
);
endwhile;
wp_reset_query();
ob_clean();
echo json_encode($send_array);
exit();
?>这很好,并正确地返回数据,除了weight属性。
这是使用Woocommerce在我的网站上设置的一个自定义属性。在我的数据库中,权重属性显示在wp_woocommerce_attribute_taxonomies表中。这个表有attribute_id、attribute_name、attribute_label等字段。
我上面用于获取产品的weight值的代码不起作用。
我也尝试过'weight' => get_post_meta( get_the_ID(), '_weight', true),但是它显示为一个空字符串(权重:“”),尽管该产品在网站上有一个权重值。
如何获得每个产品的权重,并将其添加到键weight中,就像我前面尝试的那样。
一直在做一些研究,这似乎是一个有用的项目。我做错了什么?
我该怎么解决这个问题?
发布于 2014-02-12 13:58:37
这对我来说是有效的,我得到了一个特定产品的重量。
$item_weight=wp_get_post_terms($post->ID, 'pa_weight', array("fields" => "names"));
$send_array[] = array(
'id' => get_the_ID(),
'title' => get_the_title(),
'content' => get_the_content(),
'regular_price' => get_post_meta( get_the_ID(), '_regular_price', true),
'sale_price'=> get_post_meta( get_the_ID(), '_sale_price', true),
'weight' => $item_weight[0]
);这将查看循环中定义的post,以返回pa_weight的属性值。
发布于 2017-06-28 11:21:34
global $product;
$product->get_weight();发布于 2014-02-10 17:34:16
Woo函数'woocommerce_get_product_terms‘返回一个数组。我不太熟悉Woo函数的结果,但假设它不返回多维数组,您应该将这些条件分配给$send_array数组之外的一个变量,然后尝试返回数组中的第一个项。
$weight = woocommerce_get_product_terms($product->id, 'pa_weight', 'names');然后数组将使用$weight变量,如下所示:
$send_array[] = array(
'id' => get_the_ID(),
'title' => get_the_title(),
'content' => get_the_content(),
'regular_price' => get_post_meta( get_the_ID(), '_regular_price', true),
'sale_price'=> get_post_meta( get_the_ID(), '_sale_price', true),
'weight' => $weight[0]
);如果这不起作用,您应该对变量执行var_dump($weight),以查看如何返回函数的结果。从该输出中,您应该能够确定要使用的适当索引,以获得所追求的结果。
https://stackoverflow.com/questions/21668690
复制相似问题