以下代碼用於使用Woocommerce在我的Wordpress網站上獲取「書籍」類別產品的數據。從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();
?>
這工作正常,並返回數據正確,除了weight
屬性。
這是一個使用Woocommerce在我的網站中設置的自定義屬性。在我的數據庫中,重量屬性顯示在wp_woocommerce_attribute_taxonomies
表中。此表具有字段attribute_id
,attribute_name
,attribute_label
等。
我上面用於獲取產品的weight
值的代碼不起作用。
我也試過'weight' => get_post_meta(get_the_ID(), '_weight', true)
,但它顯示爲一個空字符串(weight:「」),即使該產品在網站上有一個Weight值。
我如何獲得每種產品的重量並將其添加到陣列中,正如我上面所嘗試的weight
。
一直在做一些研究,這似乎是項目的工作。我究竟做錯了什麼?
我該如何解決這個問題?
我想這一點,但隨後爲重點'weight'顯示爲「空」的價值,當我使用'的var_dump($權重)',頁面顯示空白。沒有返回。 – Tester
你必須用'pa_'開始你的屬性鍵,所以重量應該是'pa_weight'。我爲重量設置了一個屬性來測試它,併爲我返回一個重量數組。 – pIxelnate
你的意思是在Wordpress後臺儀表板中添加前言「pa_」?或者我只需在上面的代碼中改爲「pa_weight」,即'$ weight = woocommerce_get_product_terms($ product-> id,'pa_weight','names');' – Tester