首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从Wordpress获得产品重量

从Wordpress获得产品重量
EN

Stack Overflow用户
提问于 2014-02-10 03:35:41
回答 4查看 17.6K关注 0票数 5

下面的代码是用来获取在我的Wordpress网站上使用Woocommerce的“图书”类别的产品的数据。

代码语言:javascript
复制
<?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_idattribute_nameattribute_label等字段。

我上面用于获取产品的weight值的代码不起作用。

我也尝试过'weight' => get_post_meta( get_the_ID(), '_weight', true),但是它显示为一个空字符串(权重:“”),尽管该产品在网站上有一个权重值。

如何获得每个产品的权重,并将其添加到键weight中,就像我前面尝试的那样。

一直在做一些研究,这似乎是一个有用的项目。我做错了什么?

我该怎么解决这个问题?

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2014-02-12 13:58:37

这对我来说是有效的,我得到了一个特定产品的重量。

代码语言:javascript
复制
$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的属性值。

票数 2
EN

Stack Overflow用户

发布于 2017-06-28 11:21:34

代码语言:javascript
复制
global $product;    
$product->get_weight();
票数 15
EN

Stack Overflow用户

发布于 2014-02-10 17:34:16

Woo函数'woocommerce_get_product_terms‘返回一个数组。我不太熟悉Woo函数的结果,但假设它不返回多维数组,您应该将这些条件分配给$send_array数组之外的一个变量,然后尝试返回数组中的第一个项。

代码语言:javascript
复制
$weight = woocommerce_get_product_terms($product->id, 'pa_weight', 'names');

然后数组将使用$weight变量,如下所示:

代码语言:javascript
复制
$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),以查看如何返回函数的结果。从该输出中,您应该能够确定要使用的适当索引,以获得所追求的结果。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21668690

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档