【问题标题】:Show WP category id in json在 json 中显示 WP 类别 ID
【发布时间】:2016-07-17 08:32:40
【问题描述】:

我创建了一个页面,显示来自 Wordpress 数据库的一些 json 格式的数据。现在我想显示帖子的类别ID,但它显示了对象"ads"之前的所有ID

我的来源:

<?php

header("Content-type: application/json");

include ('wp-load.php');


$loop = new WP_Query(array( 'post_status' => 'publish', 'post_type' => 'post'));
if($loop->have_posts()) : while($loop->have_posts()) : $loop->the_post();
    $posts[] = array(
        'id' => $post->ID,
        'post_title' => $post->post_title,
        'post_content' => $post->post_content,
        'guid' => $post->guid,

        'thumbnail' => (has_post_thumbnail() ? get_the_post_thumbnail_url() : ''),
        'cats' => the_category_ID(),

    );
endwhile; endif;
echo json_encode(array('ads' => $posts));

?>

【问题讨论】:

    标签: php json wordpress


    【解决方案1】:

    由于这一行,它显示了之前的 ID 'cats' =&gt; the_category_ID(),

    这个函数有什么作用?

    这个函数实际上回显了类别 ID(因为它的参数默认为 true)。

    如何解决?

    the_category_ID 中传递false 就像这样the_category_ID( false )

    更正的代码

    header("Content-type: application/json");
    
    include ('wp-load.php');
    
    
    $loop = new WP_Query(array( 'post_status' => 'publish', 'post_type' => 'post'));
    if($loop->have_posts()) : while($loop->have_posts()) : $loop->the_post();
        $posts[] = array(
            'id' => $post->ID,
            'post_title' => $post->post_title,
            'post_content' => $post->post_content,
            'guid' => $post->guid,
    
            'thumbnail' => (has_post_thumbnail() ? get_the_post_thumbnail_url() : ''),
            'cats' => the_category_ID( false ),
    
        );
    endwhile; endif;
    echo json_encode(array('ads' => $posts));
    

    【讨论】:

      【解决方案2】:
      if($loop->have_posts()) : while($loop->have_posts()) : 
          $loop->the_post();
          $posts[] = array(
              'id' => $post->ID,
              'post_title' => $post->post_title,
              'post_content' => $post->post_content,
              'guid' => $post->guid,
      
              'thumbnail' => (has_post_thumbnail() ? get_the_post_thumbnail_url() : ''),
              'cats' => the_category_ID(),
          );
          ob_clean();
      endwhile; endif;
      

      使用 ob 清洁

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-04-27
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多