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 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置