简体   繁体   中英

filter Wordpress Posts by Multiple category

I am sorting post and displaying a single category with this code.

 global $post;
    $args = array( 
        'category_name'=>'oranges',
        'numberposts'   => -1,
    );

I would like to display all post that are in both "oranges" and "apple" categories so I have modified the code I am using to display a single category to this:

global $post;
    $args = array( 
        'category_name'=>'oranges',
        'category_name'=>'apples',
        'numberposts'   => -1,
    );

This displays only the post in the apples category.
Thanks

<ul>
    <?php
    global $post;

    $myposts = get_posts( array(
        'posts_per_page' => 5,
        'offset'         => 1,
        'category'       => 1 // category id here
    ) );

    if ( $myposts ) {
        foreach ( $myposts as $post ) : 
            setup_postdata( $post ); ?>
            <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
        <?php
        endforeach;
        wp_reset_postdata();
    }
    ?>
</ul>

Thanks Arsalan for the suggestion this code here is pulling only the posts in both categories.

global $post;
    $args = array( 
        'category_name'=>'oranges + apples',
        'numberposts'   => -1,
    );

Use (+) for multiple categories

global $post;
$args = array( 
    'category_name'=>'oranges + apples',
    'numberposts'   => -1,
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM