简体   繁体   English

从WordPress $ wpdb中的get_results方法的结果中提取自定义字段

[英]Extract custom fields from results of get_results method in WordPress $wpdb

I'm working on WordPress json api plugin. 我正在研究WordPress json api插件。 I created my custom controller, I want to retrieve posts as Json format, my work was as below : 我创建了自定义控制器,我想以Json格式检索帖子,我的工作如下:

My php code is: 我的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 result as below: Json的结果如下:

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

Why price is set to null, what the correct syntax to extract price from custom fields from posts in WordPress? 为什么将price设置为null,从WordPress帖子中的自定义字段中提取价格的正确语法是什么?

thank you dears for your quick help , i found the solution , i had to use : get_post_meta function to retrieve price , so this line : 谢谢你亲爱的快速帮助,我找到了解决方案,我不得不使用:get_post_meta函数来检索价格,所以这一行:

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

will be as following : 将如下:

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

thank you , 谢谢 ,

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM