【问题标题】:Extract custom fields from results of get_results method in WordPress $wpdb从 WordPress $wpdb 中 get_results 方法的结果中提取自定义字段
【发布时间】:2016-03-31 11:27:42
【问题描述】:

我正在开发 WordPress json api 插件。我创建了我的自定义控制器,我想以 Json 格式检索帖子,我的工作如下:

我的php代码是:

$rows = $wpdb->get_results($wpdb->prepare("select * from $wpdb->posts where $wpdb->posts.post_status = 'publish' AND
            $wpdb->posts.post_title LIKE '%%%s%%' ",  $key)); 
            $count = 0 ; 
           foreach( $rows as $post ) {    
           $output[] = array( 'id' => $post->ID, 'title' => $post->post_title, 'price' =>$post->custom_fields->price);
           ++$count ; 
           }
        if($count == 0){
          $data = array ('status'=>'ok', 'count'=> $count , 'result'=> "No data found "); 
          }else
         {
          $data = array ('count'=> $count , 'result'=> $output); 
         }
       header('Content-Type: application/json; charset=UTF-8');
       return $data; 
       }

Json 结果如下:

   {
 "status": "ok",
 "count": 10,
 "result": [
  {
  "id": "51",
  "title": "a",
  "price": null
  },
  {
  "id": "82",
  "title": "b",
  "price": null
    },
     }

为什么将价格设置为空,从 WordPress 帖子的自定义字段中提取价格的正确语法是什么?

【问题讨论】:

  • 请正确格式化您的代码。
  • 做一个print_r($rows),看看你里面有什么。从你的结果$post->custom_fields->price 似乎是null...

标签: php custom-fields wordpress wordpress-json-api


【解决方案1】:

感谢亲爱的你的快速帮助,我找到了解决方案,我不得不使用:get_post_meta 函数来检索价格,所以这一行:

   $output[] = array( 'id' => $post->ID, 'title' => $post->post_title,'price' =>$post->custom_fields->price);

如下:

 $output[] = array( 'id' => $post->ID, 'title' => $post->post_title, 'price' =>get_post_meta($post->ID, 'price', true));

谢谢你,

【讨论】:

    猜你喜欢
    • 2012-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-17
    • 1970-01-01
    相关资源
    最近更新 更多