Home > Net >  How to show only posts with certain category in wordpress theme?
How to show only posts with certain category in wordpress theme?

Time:03-31

I was wondering if there is a way to change this code to only display posts from certain category created in wordpress. Now it displays every recent post. Let's say I would create "News" category in wordpress and I want this piece of code to display only News posts.

Thanks for help

<?php
        if( have_posts() ){

            while( have_posts() ){

                the_post();
                get_template_part( 'template-parts/content', 'koncert');
                
            }
        }
?>

CodePudding user response:

You can override the usual query that wordpress uses and create a custom one;

https://developer.wordpress.org/reference/classes/wp_query/

usually though for just displaying a category you can just open the category slug and provided your template has the correct archive page it will display the posts for that category.

If not use something similar to below. You can further refine your search parameters like number of posts and post types as defined in the link above.

    <?php
    
      //refine your query to the category you desire either a slug(example below) or category id
      $args = array(
        'category_name' => 'my_category_slug', 
      );
    
      //create the query using the arguments
      $query = new WP_Query($args);
    
    ?>
    
    //create the loop to show the posts
    <?php if($query->have_posts()): ?>
    
     <?php while($query->have_posts()): $query->the_post(); ?>
    
      <h1><?php the_title(); ?></h1>
    
      <div><?php the_content(); ?></div>
    
     <?php endwhile; ?>
    
    <?php endif; ?>
  • Related