Tester Tester - 1 month ago 27
PHP Question

Get product weight from Wordpress

The code below is used to get data on a products of the category "books" in my Wordpress website using 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();

?>


This works fine and returns the data correctly except for the
weight
attribute.

This is a custom attribute set in my website using Woocommerce. In my database the weight attribute shows up in the
wp_woocommerce_attribute_taxonomies
table. This table has the fields
attribute_id
,
attribute_name
,
attribute_label
etc.

The code I used above to get the
weight
value of the product doesn't work.

I also tried
'weight' => get_post_meta( get_the_ID(), '_weight', true)
, but it shows up as an empty string (weight:"") even though that product has a Weight value on the website.

How do I get the weight for each product and add it to the array to the key
weight
as I have attempted above.

Have been doing some research and this seemed to be the item to work. What am I doing wrong?

How do I fix this?

Answer

This worked for me in getting the weight of a particular product.

$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]

);

This looked at a defined post in the loop to return the attribute values for pa_weight.