Use pre_get_posts
to exclude the categories you don’t want to display in the loop.
function exclude_posts_from_specific_category( $query ) {
if ( $query->is_home() && $query->is_main_query() ) {
$query->set( 'cat', '-2' );
}
}
add_action( 'pre_get_posts', 'exclude_posts_from_specific_category' );
Or create a new WP_Query
and use the Category Parameters.
<?php
$args = array(
'category__not_in' => 2 ,
'category__in' => 4
);
$the_query = new WP_Query( $args );
if ( $the_query->have_posts() ) {
echo '<ul>';
while ( $the_query->have_posts() ) {
$the_query->the_post();
echo '<li>' . get_the_title() . '</li>';
}
echo '</ul>';
} else {
}
wp_reset_postdata();
If you only want to display posts from one category, you would use the category archive. See Template Hierarchy
.