Tes*_*ter 3 php wordpress woocommerce
下面的代码用于使用Woocommerce在我的Wordpress网站中获取“书”类产品的数据。
<?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();
?>
Run Code Online (Sandbox Code Playgroud)
这可以正常工作,并且可以正确返回该weight属性以外的数据。
这是使用Woocommerce在我的网站中设置的自定义属性。在我的数据库中,weight属性显示在wp_woocommerce_attribute_taxonomies表中。这个表中的字段attribute_id,attribute_name,attribute_label等。
我上面用来获取weight产品价值的代码不起作用。
我也尝试过'weight' => get_post_meta( get_the_ID(), '_weight', true),但是即使该产品在网站上具有“权重”值,它也显示为空字符串(“ weight:””)。
我如何尝试获得每种产品的重量并将其添加到键的数组中weight?
已经进行了一些研究,这似乎是可行的项目。我究竟做错了什么?
我该如何解决?
小智 6
global $product;
$product->get_weight();
Run Code Online (Sandbox Code Playgroud)
这对我了解特定产品的重量很有用。
$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]
);
Run Code Online (Sandbox Code Playgroud)
这查看了循环中定义的帖子以返回 的属性值pa_weight。