以json格式获取所需类别的所有帖子?

时间:2014-09-16 06:50:57

标签: php json

<?php

  include("../wp-config.php");
  // set header for json mime type
  header('Content-type: application/json;');
  $cat_id=array(12,13,14);
  $post=array('category__in' => $cat_id,'posts_per_page=-1');

  $category_query = new WP_Query($post);

// print_r($category_query);
   while ($category_query->have_posts())
  {

     $jsonpost=$category_query->the_post();
     $id=$post->ID;
     $post_title=get_the_title();
     $image=wp_get_attachment_url(get_post_thumbnail_id($id, 'thumbnail'));
     $content=strip_tags(apply_filters('the_content',$post->post_content));
    /* echo $content;
     echo $image;*/  
     $jsonpost=array('post_title'=>$post_title,'post_content' =>$content,'post_image' => $image);

    /*======== PRODUCT COLLECTION OUTPUT AS JSON FORMAT ======*/

    $output['post_details'] =  $jsonpost;
    echo (json_encode($output,JSON_UNESCAPED_SLASHES));
  }
 //print_r($jsonpost);exit();   

  $post1=array('cat'=> 12,'order' => 'DESC');
    $category_query1 = new WP_Query($post1);
     while ($category_query1->have_posts())
     {

     $jsonpost1=$category_query1->the_post();
         $id=$post->ID;
     $post_title=get_the_title();
     $image=wp_get_attachment_url(get_post_thumbnail_id($id, 'thumbnail'));
     $content=strip_tags(apply_filters('the_content',$post->post_content));
    $jsonpost1=array('post_title'=>$post_title,'post_content'=>$content,'post_image'=>$image);
     $output1['Latest_news'] =  $jsonpost1;
   /*======== PRODUCT COLLECTION OUTPUT AS JSON FORMAT ======*/

    // print_r($output);
  echo (json_encode($output1,JSON_UNESCAPED_SLASHES));
    }
  //wp_reset_postdata();

 ?>

我得到的结果如下:

{"post_details":
{"post_title":"Breaking-News2","post_content":"Lorem Ipsum is simply dummy text of the printing and typesetting industry.\n","post_image":"http://localhost/police/wp-content/uploads/2014/09/1022201314344PM_635_nokia-Lumia-1520.jpeg"}
 }
{"post_details":
{"post_title":"breaking news1","post_content":"Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia,\n","post_image":"http://localhost/police/wp-content/uploads/2014/09/breaking_news.jpg"}
 }
{"post_details":
{"post_title":"standard stories","post_content":"Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia,\n","post_image":"http://localhost/police/wp-content/uploads/2014/09/index.jpg"}
 }
{"post_details":
{"post_title":"breaking-news","post_content":"The first line of Lorem Ipsum, &#8220;Lorem ipsum dolor sit amet..&#8221;, comes from a line in section 1.10.32.\n","post_image":"http://localhost/police/wp-content/uploads/2014/09/breakingNews.jpg"}
 }
 {"post_details":
{"post_title":"call-out","post_content":"Lorem Ipsum has been the industry&#8217;s standard dummy tex\n","post_image":"http://localhost/police/wp-content/uploads/2014/09/callout.jpg"}
 }
 {"Latest_news":
{"post_title":"Breaking-News2","post_content":"Lorem Ipsum is simply dummy text of the printing and typesetting industry.\n","post_image":"http://localhost/police/wp-content/uploads/2014/09/1022201314344PM_635_nokia-Lumia-1520.jpeg"}
 }
 {"Latest_news":
{"post_title":"breaking news1","post_content":"Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia,\n","post_image":"http://localhost/police/wp-content/uploads/2014/09/breaking_news.jpg"}
 }
 {"Latest_news":
{"post_title":"breaking-news","post_content":"The first line of Lorem Ipsum, &#8220;Lorem ipsum dolor sit amet..&#8221;, comes from a line in section 1.10.32.\n","post_image":"http://localhost/police/wp-content/uploads/2014/09/breakingNews.jpg"}
 }

但我希望以下列方式显示我的回复:

{
   "post_details":
   [
       {
           "post_title": "Breaking-News2",
           "post_content": "Lorem Ipsum is simply dummy text of the printing and typesetting industry. ",
           "post_image": "http://localhost/police/wp-content/uploads/2014/09/1022201314344PM_635_nokia-Lumia-1520.jpeg"
       },
       {
           "post_title": "breaking news1",
           "post_content": "Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, ",
           "post_image": "http://localhost/police/wp-content/uploads/2014/09/breaking_news.jpg"
       },
       {
           "post_title": "standard stories",
           "post_content": "Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, ",
           "post_image": "http://localhost/police/wp-content/uploads/2014/09/index.jpg"
       },
       {
           "post_title": "breaking-news",
           "post_content": "The first line of Lorem Ipsum, “Lorem ipsum dolor sit amet..”, comes from a line in section 1.10.32. ",
           "post_image": "http://localhost/police/wp-content/uploads/2014/09/breakingNews.jpg"
       },
       {
           "post_title": "call-out",
           "post_content": "Lorem Ipsum has been the industry’s standard dummy tex ",
           "post_image": "http://localhost/police/wp-content/uploads/2014/09/callout.jpg"
       }
   ],
   "Latest_posts":
   [
       {
           "post_title": "Breaking-News2",
           "post_content": "Lorem Ipsum is simply dummy text of the printing and typesetting industry. ",
           "post_image": "http://localhost/police/wp-content/uploads/2014/09/1022201314344PM_635_nokia-Lumia-1520.jpeg"
       },
       {
           "post_title": "breaking news1",
           "post_content": "Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, ",
           "post_image": "http://localhost/police/wp-content/uploads/2014/09/breaking_news.jpg"
       },
       {
           "post_title": "breaking-news",
           "post_content": "The first line of Lorem Ipsum, “Lorem ipsum dolor sit amet..”, comes from a line in section 1.10.32. ",
           "post_image": "http://localhost/police/wp-content/uploads/2014/09/breakingNews.jpg"
       }
   ]
}

在上面的结果中,所有类别中的所有帖子都显示在单个请求数据中,但我想在第一次使用 json格式的同一数据请求中获取输出。 。所以我需要帮帮我!!

5 个答案:

答案 0 :(得分:1)

几点需要注意:

1。你不想在循环中回显json字符串。

您需要做的是在for循环中创建一个正确的关联数组。一旦通过循环和循环完成,您可以json_encode完整的关联数组并回显它。

2。不正当使用$jsonposts变量

在您引用的代码中,$jsonposts变量在循环内部用于制作立即显示的单个post数组。它可以在您需要时声明。那是在循环内部。你也可以有一个全局数组(我在代码中放了op),你可以在循环迭代中推送完整输出的每个元素,最后编码为ad send。

3。正确的代码缩进

请妥善缩进代码,以便在稍后阅读时帮助理解流程或向其他人提供支持。

include("../wp-config.php");
header('Content-type: application/json;');

/* Use this variable for preparing the result to be send back as json response */
$op = array();

$cat_args=array(
   'orderby' => 'name',
   'order' => 'ASC'
);
$categories=get_categories($cat_args);

foreach($categories as $category) 
{
    $args=array(
     'showposts' => -1,
      'category__in' => array($category->term_id),
      'caller_get_posts'=>1
     );
    $posts=get_posts($args);
    if ($posts) {
        foreach($posts as $post) {

            /* prepare individual item to be pushed into the result array */
            $jsonpost = array();
            $jsonpost['post_title']=get_the_title();
            $jsonpost['content']=apply_filters('the_content', $post->post_content); 
            $jsonpost['image_url']=wp_get_attachment_url( get_post_thumbnail_id($id, 'thumbnail') );  
            $jsonpost['date']=get_the_date('d F Y');

            /* push the item on to the result array */
            $op[] = array('request'  => 'all_posts',
                          'data'=> $jsonpost)

        }
    } 

}
/* array should be complete at this point encode it as json string and send back */
echo json_encode($op);

更新以下评论

您所显示的预期json结果是无效的json。您可以通过jsonlint.com查看相同内容。建议是将它变成

  {"request":"all_posts","data": [

    {"post_title":"Breaking News story1","content":"...."},
    {"post_title":"Breaking News story1","content":"...."},
    /* repeat elements here */

  ] }

更新为以下评论

要更改代码,它会生成类似上面提到的JSON。您必须在上述代码中进行以下更改。

更改行

$op[] = array('request'  => 'all_posts',
                      'data'=> $jsonpost);

$op[] = $jsonpost;

并从

更改最后一行
echo json_encode($op);

echo json_encode(array('request'  => 'all_posts',
                      'data'=> $op));

答案 1 :(得分:0)

试试这个

<?php
         include("../wp-config.php");
         header('Content-type: application/json;');
         $jsonpost = array();

         //for each category, show all posts
         $cat_args=array(
           'orderby' => 'name',
           'order' => 'ASC'
         );
    $categories=get_categories($cat_args);
   //print_r($categories);
   foreach($categories as $category) 
   {
     $args=array(
         'showposts' => -1,
          'category__in' => array($category->term_id),
          'caller_get_posts'=>1
         );
      //print_r($args);
      $posts=get_posts($args);
       if ($posts) {
         foreach($posts as $post) {
          //setup_postdata($post);
            $jsonpost['post_title']=get_the_title();
            $jsonpost['content']=apply_filters('the_content', $post->post_content); 
            $jsonpost['image_url']=wp_get_attachment_url( get_post_thumbnail_id($id, 'thumbnail') );  
            $jsonpost['date']=get_the_date('d F Y');

            //echo $jsonpost['post_title'];
         $output =  array('request'  => 'all_posts',
                          'data'=> $jsonpost);
          /*======== PRODUCT COLLECTION OUTPUT AS JSON FORMAT ====== */


    } // foreach($posts
  echo (json_encode($output));
  } // if ($posts

}   // foreach($categories

答案 2 :(得分:0)

你能试试下面的代码。

<?php
     include("../wp-config.php");
     header('Content-type: application/json;');
     // create new array to add all posts to
     $jsonposts = array();

     //for each category, show all posts
     $cat_args=array(
       'orderby' => 'name',
       'order' => 'ASC'
     );
    $categories=get_categories($cat_args);
    //print_r($categories);
    foreach($categories as $category) 
    {
      $args=array(
         'showposts' => -1,
          'category__in' => array($category->term_id),
          'caller_get_posts'=>1
         );
      //print_r($args);
      $posts=get_posts($args);
       if ($posts) {
         foreach($posts as $post) {
          //setup_postdata($post);
            $jsonpost = array();
            $jsonpost['post_title']=get_the_title();
            $jsonpost['content']=apply_filters('the_content', $post->post_content); 
            $jsonpost['image_url']=wp_get_attachment_url( get_post_thumbnail_id($id, 'thumbnail') );  
            $jsonpost['date']=get_the_date('d F Y');

            //echo $jsonpost['post_title'];
            // add the post to the new array
            $jsonposts[] = $jsonpost;

          /*======== PRODUCT COLLECTION OUTPUT AS JSON FORMAT ====== */


    } // foreach($posts
     // format as JSON
     $output =  array('request'  => 'all_posts',
                          'data'=> $jsonposts);
     echo (json_encode($output));

  } // if ($posts

}   // foreach($categories

答案 3 :(得分:0)

使用WordPress REST API:https://wordpress.org/plugins/json-rest-api/

获取这样的网址:

http://your-site.com/wp-json/posts?filter[category_name]=dogs

请注意,API的根URL可以随过滤器更改,不要假设其默认值。请改用json_url()

使用WordPress HTTP API:

$response = wp_remote_get( $url, json_url() );

//make sure response isn't an error
if ( ! is_wp_error( $response )  ) {

    //get the posts as an array
   $posts = json_decode( wp_remote_retrieve_body( $response ) );
}

使用jQuery / AJAX:

$.ajax({
        type: 'GET',
        cache: true,
        url: rootURL + '/posts?filter[category_name]=dogs,
        dataType: 'json',
        success: function(posts) {
            //do stuff with posts
        }
    });

对于jQuery / AJAX示例,请务必使用json_url()wp_localize_script()的值本地化到DOM中。

答案 4 :(得分:0)

首先需要注册GET方法的功能。语法如下。

  // GET All Posts using API
  add_action( 'rest_api_init', 'wp_api_show_Posts_endpoints' );
  function wp_api_show_Posts_endpoints() {
    register_rest_route( 'showPost', '/v2', array(
          'methods' => 'GET',
          'callback' => 'showPosts_callback',
      ));
  }

这里我为逻辑采用了 showPosts_callback 函数(其内容需要在json视图上获取)

这是 GET方法逻辑的回调函数

  function showPosts_callback( $request_data ) {
    global $wpdb;
    $data = array();

    $table        = 'wp_posts';
    $parameters = $request_data->get_params();
    $post_type = $parameters['post_type'];

    if($post_type!=''){
        $re_query     = "SELECT * FROM $table where post_type='$post_type'";
        $pre_results  = $wpdb->get_results($re_query,ARRAY_A); 
        foreach ($pre_results as $key => $value) {
            $post_id = $value['ID'];

            // Adding selected categories
            $post_categories = wp_get_post_categories( $post_id );
            $cats = array();

            foreach($post_categories as $c){
                $cat = get_category( $c );
                $cats[] = array( 'name' => $cat->name, 'slug' => $cat->slug );
            }
            $pre_results[$key]['all_selected_categories']=$cats;

            // Adding post featured image.
            $featured_img_url = get_the_post_thumbnail_url($post_id, 'full'); 
            $pre_results[$key]['featured_img_url']=$featured_img_url;

            // Adding post metaboxes
            $meta = array();
            $meta = get_metadata($post_type,$post_id);
            $pre_results[$key]['metafields'] = $meta;

          }
        return $pre_results;

    }else{
        $data['status']=' false ';
        return $data;

    } 
  }

然后您可以使用此URL

从任何地方获取记录
Syntax:
 www.yourdomain.com/wp-json/showPost/v2?post_type=post