Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display posts of certain category from multiple custom post types

I'm trying to make a "Meal of the month" section on a website. The menu is split in custom post types so I need to be able to loop the category from multiple post types.

This is the code I have so far which does absolutely nothing:

<div class="maaltijd-vdm col-1-1">
                <?php   $mvdm = new WP_Query( array( 'category_name' => 'mvdm', 'posts_per_page' => 1 ) ); ?>
                <?php   while ($mvdm->have_posts()) : $mvdm->the_post(); ?>

                    <div class="mvdm-thumb">
                        <?php the_thumbnail(); ?>
                    </div>

                    <div class="description">
                        <h3><?php the_title(); ?></h3>
                        <p><?php get_the_mvdm(); ?></p>
                    </div>

                <?php   endwhile; wp_reset_postdata(); ?>

            </div>

I would really appreciate your help!

*get_the_mvdm is a custom function

*I already have a news loop in the same page with the same code (except variable name)

like image 293
Kevin Tad Avatar asked Nov 18 '25 07:11

Kevin Tad


2 Answers

To query for multiple posttypes, you can pass an array of the post-type slugs to the query.

$args = array(
    'post_type'         => array('cpt1', 'cpt2'),   /* the names of you custom post types */
    'category_name'     => 'mvdm',
    'posts_per_page'    => -1                       /* get all posts */
)

$mvdm = new WP_Query( $args );
like image 138
xphan Avatar answered Nov 20 '25 21:11

xphan


You must use tax_query for get posts by category.

Try this code:

$tags_args = array(
                'post_type' => array(cpt1, cpt2, cpt3 ....),
                'posts_per_page' => 999,
                'order' => 'DESC',
                'tax_query' => array(
                                    array(
                                        'taxonomy' => 'Your Taxonomy',
                                        'field' => 'slug',
                                        'terms' => 'Your term slug'
                                    )
                                )
                            );
            $tags_qry = new WP_Query($tags_args);

            while($tags_qry->have_posts()) :
                $tags_qry->the_post();

                // Your Code
            endwhile

Hope you find your solution.

like image 21
deemi-D-nadeem Avatar answered Nov 20 '25 19:11

deemi-D-nadeem



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!