douduanque5850 2012-03-28 15:17
浏览 54

手动检索带有JSON类别/标签的Wordpress帖子

I'm trying to manually query the wordpress database to retrieve specific post content for a json feed. In theory I want to return a number of 'Post' objects with each containing a 'tags/categories' array within it of each tag/category.

I'm currently using the following SQL query to retrieve the posts I want, however I think I am missing a relationship between the wp_term_taxonomy table, as well as this returns a unique row per tag/category:

SELECT wp_posts.post_date, wp_posts.post_content, wp_posts.post_title, wp_posts.ID, wp_terms.name
FROM wp_posts
LEFT JOIN wp_term_relationships ON ( wp_term_relationships.object_id = wp_posts.ID ) 
LEFT JOIN wp_terms ON ( wp_terms.term_id = wp_term_relationships.term_taxonomy_id ) 
WHERE 1=1
AND wp_posts.post_type = 'post'
AND (wp_posts.post_status = 'publish')
ORDER BY wp_posts.ID DESC 
LIMIT 25

Anyone got any advice on how I can achieve my goal? What I didnt want to do is do one query to get the posts, then iterate through each one and query to get and set the tag/category array - but maybe that's my only option?

  • 写回答

3条回答 默认 最新

  • dtf0925 2012-06-22 17:20
    关注

    If you are trying to make it possible to retrieve information from WordPress through JSON, it makes more sense to have a page in WordPress serve as the request URL:

    Say the URL is yourwebsite.com/request/?posts_per_page=10; you create a page in WordPress with that slug, and then use a page template with only the following code inside it:

    $parameters = array(
        'post_type' => 'post',
            'posts_per_page' => $_GET['posts_per_page']
        );
    }
    $requested_object = get_posts($parameters);
    
    // if we have a request
    if (!empty($requested_object)) {
    
        foreach ($requested_object as $post) :  setup_postdata($post); 
    
            // build the json request
            // you can make your arrays of tags & categories here
            $json_request[] = array(
                'id' => get_the_ID(),
                'title' => get_the_title(),
                'content' => apply_filters('the_content',$post->post_content)
            );
    
        endforeach;
    
        // return the json request
        header('Content-type: application/json');
        echo json_encode($json_request);
    

    When your javascript requests /request/?posts_per_page=10, it will get JSON with 10 posts and all the attributes you want.

    评论

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大