Posts by category in home page, simple tutorial to learn how to display posts by category in wordpress.

How To Display Posts By Category WordPress?

Using query_posts() function and pre_get_posts action, we have two ways to display posts by category wordpress.

Using Functions File

This is way for websites owner, just copy function and paste it in functions.php file:

function display_posts_by_cat( $query ) {
if ( $query->is_home() ) {
$query->set( 'category_name', 'plugins,themes' );
}
}
add_action( 'pre_get_posts', 'display_posts_by_cat' );

Replace ‘plugins,themes’ to your category names, for example ‘movies,sport’, now in home page will be display posts from movies and sport category, if you want to display posts from one category, just enter your category name without a comma, for example ‘movies’, now in home page will be display posts from movies category only.

Display posts from all categories and exclude some categories:


function excluding_cats_from_homepage( $query ) {
if ( $query->is_home() ) {
$query->set( 'category__not_in', array(3) );
}
}
add_action( 'pre_get_posts', 'excluding_cats_from_homepage' );

Replace number 3 from array(3) and enter category ID to excluding it, for example your movies category has ID number 50, enter array(50), now in home page will be display posts from all categories and exclude movies category, for excluding multi categories, use a comma array(50,60).

Themes Developer

This way for themes developer, but you can use it, find your loop in index.php file, anyway paste query_posts(‘cat=here enter cat ID’) before your loop, for example:

<?php
query_posts( 'cat=3' ); // will be display posts from category ID number 3
// or query_posts('category_name=movies'); display movies category posts

while (have_posts()) : the_post();
the_content();
endwhile;
?>

For multi categories, add it before your loop:

query_posts('cat=3,4'); // display posts by category ID number 3 & 4
//or query_posts('category_name=movies,sport'); display posts from movies and sport category

You can using get_cat_ID() function to get category ID by name, for example:

<?php
get_cat_ID('movies'); // will be return ID of movies category
?>

Read more info about posts by category wordpress.