Hej, I'll keep it short. I want to output this in a WP loop:
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 ).
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. I believe I need some sort of foreach
but I can't really figure it out. Any suggestions?
/edit/
The current display looks like this:
Support, Category1
Post1
---
Support, Category2
PostA
---
Support, Category1
Post2
etc.
To display your custom post types on the same category page as your default posts, you need to add this code into your theme's functions. php or a site-specific plugin. $post_type = array ( 'nav_menu_item' , 'post' , 'movies' ); // don't forget nav_menu_item to allow menus to work!
First, you can simply go to Appearance » Menus and add a custom link to your menu. This custom link is the link to your custom post type. Don't forget to replace 'example.com' with your own domain name and 'movies' with your custom post type name.
To do that, simply edit any existing post or add a new one. Once you're in the WordPress editor, go ahead and click the '+' icon and add a 'Popular Posts' block where you want it to appear in your content. The plugin will automatically add your most popular articles and display them as related posts.
Avoid post__not_inIt's usually used to exclude certain post IDs from a query's results.
Here is how you do it. You needed a foreach loop to cycle through the categories.
<?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,
));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With