Categories overview that links to page displaying posts

I am trying to achieve the following

A page that displays a series of categories with a title, description and an image

When a category is clicked, all posts that belongs to that category gets shown.

I see 2 ways to achieve this:

I could create a custom taxonomy, ad an image field and list all the categories in this taxonomy in a custom template. How to handle the templating for displaying the posts when a category is clicked, I am not sure of.

I could create a template with categories registered and saved with wp_option, then from each post choose a category, then make a custom query to select all posts in that category. Again I am not sure which type of template to create.

What is the correct way to achieve this?

Answers 1

  • There is no need to create a custom taxonomy or custom template.

    When we click on any category then wordpress by default called archive.php file which has code for display posts related to that particular category.

    So first use this code in any of your php template file to display category lists:

    <?php
    $args = array(
      'orderby' => 'name',
      'order' => 'ASC'
    );
    echo '<ul>';
    $categories = get_categories($args);
    foreach($categories as $category) { 
        echo '<li><a href="' . get_category_link( $category->term_id ) . '" title="' . $category->name . '" ' . '>' . $category->name.'</a></li>';
    } 
    echo '</ul>';
    ?>
    

    Which display category titles, likewise you also can display category descriptions and images.

    And when you click on the category title, then it will call wordpress archive.php file which display posts related to that particular categoty.


Related Questions