Skip to content
Advertisement

How to show only posts from one category on page? [WordPress]

I’ve created my own WordPress Theme by using a video tutorial.

In this theme I created a page-ID.php where only posts from one category should be shown.

How can I accomplish this?

Current code where I tried to call the category (ID 12):

<?php 
                    
$number_of_posts = get_option('post_per_page', 10);
$paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1;
$offset = ($paged - 1) * number_of_posts;
                    
$args = array(
    post_type => 'post',
    posts_per_page => '5',
    offset => $offset,
    paged => $paged,
    cat => '-12' // ID of category
);
                    
$loop2 = new WP_Query($args);
                    
if ( $loop2->have_posts() ) : while ( $loop2->have_posts() ) : $loop2->the_post();?>
                    
    <?php if (has_category()) { get_template_part('template_parts/content'); };?>
                    
<?php endwhile; else : ?>
                    
    <?php get_template_part('template_parts/content','error');?>
                    
<?php endif;?>
                            
<?php previous_posts_link('Vorherige Seite', $loop2->max_num_pages);?>
<?php next_posts_link('Nächste Seite', $loop2->max_num_pages);?>
                    
<?php wp_reset_postdata();?>

If I use it like this posts with other categories like ID 1 and ID 13 are shown but not with the defined one (ID 1 = Uncategorized; ID 12 = Latest; ID 13 = Events). My goal is the opposite.

Can you tell me what I did wrong?

Advertisement

Answer

You have cat => '-12' in your code – that would be category ID minus 12. Change that to cat => '12'

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement