[英]WP_Query to display posts by category in Wordpress (in custom post types)
Hej, I'll keep it short. Hej,我会保持简短。 I want to output this in a WP loop:我想在 WP 循环中输出这个:
Support
Category1
-Post1
-Post2
Category2
-PostA
-PostB
-PostC
So I want to order posts by category that are located in a custom post type - support
(created thanks to Types plugin, link: ujeb.se/A4zqZ ).所以我想按位于自定义帖子类型中的类别订购帖子 - support
(由于类型插件创建,链接: ujeb.se/A4zqZ )。
I have this:我有这个:
<?php
$args = array('post_type' => 'support');
$query = new WP_Query($args);
while($query -> have_posts()) : $query -> the_post(); ?>
<p><?php the_category(); ?></p>
<h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
<p><?php the_content(); ?></p>
<?php endwhile; ?>
My $query
stores all the necessary posts from my custom post type ( support
) but I have a problem with displaying them by category.我的$query
存储来自我的自定义帖子类型 ( support
) 的所有必要帖子,但我在按类别显示它们时遇到问题。 I believe I need some sort of foreach
but I can't really figure it out.我相信我需要某种foreach
但我无法真正弄清楚。 Any suggestions?有什么建议?
/edit/ /编辑/
The current display looks like this:当前显示如下:
Support, Category1
Post1
---
Support, Category2
PostA
---
Support, Category1
Post2
etc.
Here is how you do it.这是你如何做到的。 You needed a foreach loop to cycle through the categories.您需要一个 foreach 循环来循环浏览类别。
<?php
$cats = get_categories();
foreach ($cats as $cat) {
$args = array(
'post_type' => 'support',
'tax_query' => array(
array(
'taxonomy' => 'category',
'field' => 'term_id',
'terms' => $cat->cat_ID,
),
),
);
$query = new WP_Query($args);
if ( $query->have_posts() ): ?>
<p><?php echo $cat->cat_name ; ?></p> <?
while($query -> have_posts()) : $query -> the_post(); ?>
<h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
<p><?php the_content(); ?></p> <?php
endwhile;
endif;
// Added this now
wp_reset_query() ;
}
this work for me:这对我有用:
$posts = new WP_Query(array(
'category_name' => 'news,
'post_status' => 'publish',
'post_type' => 'post',
'posts_per_page' => 6,
));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.