How can I display recent posts from a particular category in my header?

You do want to “do a loop”.

Within your header you want to make a fresh query for just those three posts and loop through them without upsetting the main query that you need further down each page.

Here’s a standard loop calling three posts from your category:

$wpse_235359_query = new WP_Query( array( 

        'category_name' => 'your-category-slug',
        // should pull in posts from child categories too

        'posts_per_page' => 3 

    ) );

if ($wpse_235359_query->have_posts()) :

    while($wpse_235359_query->have_posts()) :
        $wpse_235359_query->the_post();

        /* show your post stuff here using standard
           template tags like the_title()
        */

    endwhile;

endif;

wp_reset_postdata();

Calling wp_reset_postdata at the end sets everything back nicely so the rest of your page behaves as expected.

You put this snippet of code anywhere in your theme files that you’d like to show this bundle of posts. That can be in a child theme if you’re basing your theme upon another, or in the main theme files if you’re building the whole theme.

Edit – additions from the comments to keep the comment list shorter

Call the variable $wpse_235359_query anything you like. Use the snippet multiple times with different categories if you wish.

Place it where you want, using a child theme so you can still update your parent theme. The child theme works by overriding whole template files in the parent. So you copy the parent header.php into the child theme, modify it, and the child header.php is used by WP instead of the parent header.php. A call to load header.php will always look in the child theme first.

Then to style the first differently, using HTML like this:

<div>
    <span class="MainCategoryHeader">
    <a href="http://www.example.com/">Permalink One</a>
        </span>
    <span class="MainCategoryHeader">
        <a href="http://www.example.com/">Permalink Two</a>
    </span>
    <span class="MainCategoryHeader">
        <a href="http://www.example.com/">Permalink Three</a>
    </span>
</div>

Apply CSS like this:

.MainCategoryHeader:first-child a { 
    background-color: #FFFFFF; 
    color: #FFFF00; 
} 
.MainCategoryHeader a { 
    background-color: #FFFFFF; 
    color: #000000; 
}

This has strayed a long way from WordPress and the main point of the original question now though. If you’re happy that the WordPress part is solved then please do accept the answer, not just for my benefit but to keep the site tidy too.

Leave a Comment