1

我正在开发 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 帖子中的自定义字段中提取价格的正确语法是什么?

4

1 回答 1

0

谢谢亲爱的你的快速帮助,我找到了解决方案,我不得不使用: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));

谢谢你 ,

于 2016-03-31T12:11:19.113 回答