我正在尝试创建一个自定义循环,它将显示所选类别中的最新5篇文章,所有这些都使用一个查询。我希望循环显示类别名称,后跟5篇文章,然后是下一个类别,等等。
我跟着this answer 它似乎做了我想做的,只是它不能正确输出类别。
例如,假设我想显示类别100101102和103,它应该显示如下:
100
Post 1
Post 2
Post 3
Post 4
Post 5
101
Post 1
Post 2
Post 3
Post 4
Post 5
等
问题However, 目前,如果100类和250类中都有帖子,那么它也会显示250类的标题,如下所示
250
Post 1
如何使其仅显示指定的类别
这是我目前掌握的代码,基于
this.
<?php
$args = array(
\'posts_per_page\' => -1,
\'tax_query\' => array(
array(
// arguments for your query
\'taxonomy\' => \'category\',
\'field\' => \'id\',
\'terms\' => $selected_categories, // $selected_categories contains an array of post IDs.
)
)
);
$query = new WP_Query($args);
$q = array();
while ( $query->have_posts() ) {
$query->the_post();
$a = \'<a href="\'. get_permalink() .\'">\' . get_the_title() .\'</a>\';
$categories = get_the_category();
foreach ( $categories as $key=>$category ) {
$b = \'<a href="\' . get_category_link( $category ) . \'">\' . $category->name . \'</a>\';
}
$q[$b][] = $a; // Create an array with the category names and post titles
}
/* Restore original Post Data */
wp_reset_postdata();
foreach ($q as $key=>$values) {
echo $key;
echo \'<ul>\';
foreach ($values as $value){
echo \'<li>\' . $value . \'</li>\';
}
echo \'</ul>\';
}
?>
谢谢你的帮助!
最合适的回答,由SO网友:Karthick 整理而成
我用过Custom Select Query 在一次电话中收集所有信息,并希望它能奏效。
global $wpdb;
$selected_cat_id = \'6,7,8,9\';
$post_count = 5;
$custom_query = "SELECT $wpdb->posts.ID, $wpdb->posts.post_title, $wpdb->terms.name FROM $wpdb->posts
LEFT JOIN $wpdb->term_relationships ON ($wpdb->posts.ID = $wpdb->term_relationships.object_id)
LEFT JOIN $wpdb->terms ON ($wpdb->term_relationships.term_taxonomy_id = $wpdb->terms.term_id)
WHERE 1=1 AND ($wpdb->term_relationships.term_taxonomy_id IN ($selected_cat_id))
AND $wpdb->posts.post_type = \'post\' AND ($wpdb->posts.post_status = \'publish\' OR $wpdb->posts.post_status = \'private\') ORDER BY $wpdb->posts.post_date ASC";
$pageposts = $wpdb->get_results($custom_query, OBJECT);
$cat_posts = array();
foreach($pageposts as $post){
$cat_posts[$post->name][$post->ID] = $post->post_title;
}
foreach($cat_posts as $key => $values) {
$category_id = get_cat_ID( $key );
echo \'<a href="\'.get_category_link($category_id).\'">\'.$key.\'</a>\';
$values = array_slice($values,0,$post_count,true);
echo \'<ul>\';
foreach ($values as $post_id => $value){
echo \'<li><a href="\'.get_permalink($post_id).\'">\' . $value . \'</a></li>\';
}
echo \'</ul>\';
}