admin管理员组

文章数量:1425861

looking to create a page that will show all posts from several categories. for example lets say I want all of my posts from category 1, 5, and 9 together. the posts on the page should be ones from any of those categories and aren't required to be in multiple of them or all of them. is it possible to do this?

looking to create a page that will show all posts from several categories. for example lets say I want all of my posts from category 1, 5, and 9 together. the posts on the page should be ones from any of those categories and aren't required to be in multiple of them or all of them. is it possible to do this?

Share Improve this question asked May 31, 2019 at 18:38 ZakZak 131 silver badge3 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 2

To display a custom query in a single page you would need to create a new page template and assign that to a page.

  1. Create a file in your theme's main folder and call it multiple-categories.php
  2. Paste the following code in the file

    <?php
    /* Template Name: Multiple Categories */
    
    get_header();
    
    $args = array(
        'cat' => '1, 5, 9',
        'posts_per_page' => -1,
    );
    
    $my_posts = new WP_Query( $args );
    
    if( $my_posts->have_posts() ){
        while( $my_posts->have_posts() ){
            $my_posts->the_post();
            //Echo the post
        }
    }
    wp_reset_postdata();
    
    get_footer();
    
  3. Create a new page and in the template field select "Multiple categories".

Visiting that page you should see the articles from any of those categories. The template file and name is just an example and can be changed at will without using the default ones listed here https://developer.wordpress/themes/basics/template-hierarchy/

More details about the arguments for the query relative to categories can be found here: https://codex.wordpress/Class_Reference/WP_Query#Category_Parameters

本文标签: How to create a page that shows posts from multiple categories