It's fairly easy to understand. When you define a new custom query (a custom loop), you're referencing a multitude of arguments against it.
In your case we are interested by the categories parameters.
Category Parameters
Show posts associated with certain categories.
- cat (int) – use category id.
- category_name (string) – use category slug.
- category__and (array) – use category id.
- category__in (array) – use category id.
- category__not_in (array) – use category id.
We are going to use the category__in
and category__not_in
parameters. And we will be fetching the category id via the category slug using get_category_by_slug
.
Here is our final result. I've added comments, you can add more arguments of you want by looking at the CODEX to view the full list. Modify and have fun!
<?php
// Column A
$x = get_category_by_slug( 'category_x_slug' )->term_id; // ... get category x ID
$y = get_category_by_slug( 'category_y_slug' )->term_id; // ... get category y ID
$args = [
'post_type' => 'post'
'posts_per_page' => 6,
'category__in' => [ $x, $y, ], // ... Column A: post with category x, category y
];
$query = new WP_Query( $args ); // ... loop start
if( $query->have_posts() ):
while( $query->have_posts() ): $query->the_post();
// ... post template start
the_title( '<h1>', '</h1>' );
the_excerpt();
// ... post template end
endwhile;
else:
echo "No posts yet!";
endif; // ... loop end
wp_reset_postdata(); ?>
<?php
// Column B
$x = get_category_by_slug( 'category_x_slug' )->term_id;
$y = get_category_by_slug( 'category_y_slug' )->term_id;
$args = [
'post_type' => 'post'
'posts_per_page' => 6,
'category__in' => [ $x, ], // ... Column B: post with category x
'category__not_in' => [ $y, ], // ... Without post with category y
];
$query = new WP_Query( $args ); // ... loop start
if( $query->have_posts() ):
while( $query->have_posts() ): $query->the_post();
// ... post template start
the_title( '<h1>', '</h1>' );
the_excerpt();
// ... post template end
endwhile;
else:
echo "No posts yet!";
endif; // ... loop end
wp_reset_postdata(); ?>
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…