Add a Topic page to WordPress

Do you want to have an introduction to a category of posts (or by a tag). Add a page template to your theme for topic pages.

All the articles in this site are categorized. The menus are based on these categories, but there is a topic page to introduce each category. After the introduction there is a list of all articles in the category (the featured image, title and excerpt). This kind of topic page template is not typically included in WordPress themes, but you can roll your own.

Automation is the way to ease administraton. In this code example the page slug automatically determines the category of the posts displayed. E.g. if the page slug is "wordpress" then all posts in "wordpress" category are displayed at the end of the page (to be precise, the category slug is "wordpress"). You can also make such a topic page template for keywords.

Copy page.php to topic.php. If there is no page.php in your theme, copy it from the parent theme. Add Template Name to the comments at the top:

/**
 * The template for displaying topic pages
 *
Template Name: Topic
 *
 */

Towards the end of topic.php, but inside of the main <div> (or <main> element, if there is one), add:

<?php
$args = array( 
    'category_name' => get_post_field( 'post_name' ),
    'numberposts' => -1,     // All posts
    'orderby' => 'title',    // Alphabetically
    'order' => 'ASC'         // From A to Z
);
$topicposts = get_posts( $args );

foreach ( $topicposts as $post ) {
    setup_postdata( $post );
    ?>
    <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
    <?php if ( has_post_thumbnail() ) { the_post_thumbnail('thumbnail'); } ?>
    <header class="entry-header listing">
        <a href="<?php the_permalink(); ?>">
            <?php the_title( sprintf( '<h3>', '</h3>' )); ?>
        </a>
    </header><!-- .entry-header -->
    <?php the_excerpt(); ?>
    </article><!-- #post-## -->
<?php    
}
wp_reset_postdata();
?>

There is one caveat: There are <?php and ?> at the beginning and end of the code. They are needed if the code is inserted inside of HTML code, but should be removed if inserted inside PHP code.

The $args at the beginning defines the posts to be displayed. The most important is the first one, where category_name field gets the value of the current page slug. If you want to use keywords instead, use 'tag' => get_post_field( 'post_name' ). The other fields control the count and ordering of the posts. Removing those lines would get you the defaults (5 articles at a time, ordered by time published, newest first).

To use:

  1. Create a new page and use page template Topic
  2. Type in the introduction you want
  3. Use the same value for the page slug as the slug for the category (or tag)

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.