Amend theme php to include certain category in header

I’m using a free theme on my WordPress site, and the index.php is the following:

<?php if (have_posts()) : ?>

    <?php
    $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
    $total_post_count = wp_count_posts();
    $published_post_count = $total_post_count->publish;
    $total_pages = ceil( $published_post_count / $posts_per_page );

    if ( "1" < $paged ) : ?>

        <div class="page-title">

            <h4><?php printf( __('Page %s of %s', 'hitchcock'), $paged, $wp_query->max_num_pages ); ?></h4>

        </div> <!-- /page-title -->

        <div class="clear"></div>

    <?php endif; ?>

    <div class="posts" id="posts">


        <?php while (have_posts()) : the_post() ; ?>


            <?php get_template_part( 'content', get_post_format() ); ?>

        <?php endwhile; ?>

        <div class="clear"></div>

    </div> <!-- /posts -->

<?php endif; ?>

<div class="clear"></div>

<?php hitchcock_archive_navigation(); ?>

This shows the latest posts on my website. I want to amend this code to only show posts from a certain category instead. Is this something that I can just amend or add code?

1

Answers


  1. Alex
    0 Votes

    You can use the action pre_get_posts. It gets fired after the query object is created but before the query is run.

    This is an example from the official documentary for displaying only one category:

    In your functions.php add the following:

    function my_home_category( $query ) {
        if ( $query->is_home() && $query->is_main_query() ) {
            $query->set( 'cat', '123' );
        }
    }
    
    add_action( 'pre_get_posts', 'my_home_category' );
    
Please signup or login to answer this question.

Signup for an account and start participating in our site today!




Social Signup

You can also login with your Facebook, Twitter or Linkedin account

Log in with Facebook