我想在外部应用程序中获取每个类别最新的5个已发布的WordPress帖子。这些应用程序是在ASP.NET中构建的,因此我想使用EF直接从MySQL数据库中获取数据。在EF中构建WordPress关系似乎很糟糕所以我想构建一个自定义模型,其中包含类别详细信息和有关最新帖子的信息。
所以我写了一个有效的SQL查询,但由于它的聚合组给了我每个类别只有一行(帖子):
Select terms.term_id As Id, terms.name As Name, terms.slug As SeoName, Group_Concat(relations.object_id) As PostId, taxonomy.count As Count, taxonomy.parent As ParentId,
(
Select post_title
From wp_posts
Where ID In(Group_Concat(relations.object_id))
Order By post_date Desc
) As PostTitle
From wp_terms terms, wp_term_taxonomy taxonomy, wp_term_relationships relations
Where terms.term_id = taxonomy.term_id
And relations.term_taxonomy_id = taxonomy.term_taxonomy_id
And taxonomy.taxonomy = 'category'
Group By terms.term_id
我的想法是添加Having Count(terms.term_id) = 5
,以便每个类别获得5行。但是它没有用,我得到了一个空洞的结果。如果没有Having
,我会在每个类别中使用最新帖子获得一行。
如何在不删除分组的情况下告诉MySQL每个类别返回5行?
假设我有树类:
然后我想从数据库中获得以下结果(简而言之):
CategoryId | CategoryName | NewestPostTitle
1 | CatA | Newest post in CatA
1 | CatA | Second newest post in CatA
...
2 | CatB | Newest post in CatB
2 | CatB | Second newest post in CatB
...
3 | CatC | Newest post in CatC
3 | CatC | Second newest post in CatC
答案 0 :(得分:0)
为什么你不使用内置的wordpress功能?请尝试下面的代码,我已经对它进行了测试,它适用于我的测试:
$categories = get_categories();
/* echo '<pre>';
print_r($categories);
echo '</pre>'; */
foreach($categories as $category){
$args = array(
'posts_per_page' => 5,
'cat' => $category->term_id,
'orderby' => 'ID',
'order' => 'DESC'
);
$query = new WP_Query($args);
echo $category->name . '<hr />';
while($query->have_posts()):$query->the_post();
echo the_title() . '<br />';
endwhile;
}
编辑:我没有意识到你想在外部应用程序中使用它。我会使用我提供的代码并创建一个页面模板,它将以数组或json格式返回结果。
你也可以回应查询wordpress用来抓取数据并建立起来。您可以通过回显$ query-&gt; request;
来实现e.g。
通过以下方式获取wordpress类别列表:
SELECT t.term_id AS id
FROM wp_terms t
LEFT JOIN wp_term_taxonomy tt
ON t.term_id = tt.term_id
WHERE tt.taxonomy = 'category'
ORDER BY name
循环搜索结果并从term_id中获取最新的5个条目:
SELECT SQL_CALC_FOUND_ROWS wp_posts.ID FROM wp_posts LEFT JOIN wp_term_relationships ON (wp_posts.ID = wp_term_relationships.object_id) WHERE 1=1 AND ( wp_term_relationships.term_taxonomy_id IN (5) ) AND wp_posts.post_type = 'post' AND (wp_posts.post_status = 'publish' OR wp_posts.post_status = 'private') GROUP BY wp_posts.ID ORDER BY wp_posts.ID DESC LIMIT 0, 5
将wp_term_relationships.term_taxonomy_id IN (6)
替换为循环中的相应ID。