Retrive Posts From Specific Category And Show it on A Template Page

First wee need to create a page template in wordpress. For that create a file called template-category.php in the theme directory and then add the below comment at the top of the file.

template-category.php

<?php
/**
 * Template Name: Category Custom Page
 */
 
?>

Now from the dashboard of the wordpress , create a page where you want to display the posts. Assign our template to this page.

Custom Category Page

OK, Now its time to Retrive Posts From Specific Category.

We will use WP_Query class to retrive the posts. Suppose we have a category named as ‘ PHP ‘ which posts need to display.

$args = array(
    'post_type' => 'post',
    'post_status' => 'publish',
    'category_name' => 'wordpress',
    'posts_per_page' => 5,
);
$arr_posts = new WP_Query( $args );
 
if ( $arr_posts->have_posts() ) :
 
    while ( $arr_posts->have_posts() ) :
        $arr_posts->the_post();
        ?>
        <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
            <?php
            if ( has_post_thumbnail() ) :
                the_post_thumbnail();
            endif;
            ?>
            <header class="entry-header">
                <h1 class="entry-title"><?php the_title(); ?></h1>
            </header>
            <div class="entry-content">
                <?php the_excerpt(); ?>
                <a href="<?php the_permalink(); ?>">Read More</a>
            </div>
        </article>
        <?php
    endwhile;
endif;

In ttha above code we have passed ‘category_name’ => ‘ PHP’. Here ‘PHP’ is the slug of a category/

We can also pass category id instead of category_name.

$args = array(
    'post_type' => 'post',
    'post_status' => 'publish',
    'cat' => '4', //we can pass comma-separated ids here
    'posts_per_page' => 5,
);

posts_per_page is the number of posts to fetch from the database. We have used have_posts() method which checks whether posts are available for WordPress loop. If posts are available then we loop through each post and display it.