Phillip Schikora
Phillip Schikora

Reputation: 37

Wordpress: How to show posts from a specific category via the loop?

I have a menu bar with different topics (technology, food, etc.) When I click on one of those, I would like to display all posts that have that specific topic assigned. Everything I have found online shows me how to do this by specifying the topic using an ID. However, I do not want to "hard code" it, but rather run a function that gets the name of the page, and then displays posts that correspond to that category. So essentially, instead of having cat=1 in my query argument, I would like to enter code that gets the title of the page, as the title of the page equals the category I want to show. I have posted the first part of my code below. My loop works fine other than that and displays the content how I want it to. I just need to figure out how to dynamically fetch the page title and assign that as the category value. Thank you for any help

<?php query_posts('cat=1'); ?>
    <?php if (have_posts()) : while (have_posts()) : the_post(); ?>

Upvotes: 0

Views: 92

Answers (2)

Ruhul Amin
Ruhul Amin

Reputation: 1775

If you want to use Custom template:

The idea can be. You need to use page(in the menu) same as category slug.

Then get page slug using:

<?php global $post; $post_slug=$post->post_name; ?>

Complete code for template:

global $post;
$post_slug=$post->post_name;

 $args = array( 'category_name' => $post_slug );
// The Query
$the_query = new WP_Query( $args );

// The Loop
if ( $the_query->have_posts() ) {
echo '<ul>';
while ( $the_query->have_posts() ) {
    $the_query->the_post();
    echo '<li>' . get_the_title() . '</li>';
}
echo '</ul>';
/* Restore original Post Data */
wp_reset_postdata();
} else {
// no posts found
}

OR you can add those categories into menu from Appearance>>Menus and then

  1. category.php or
  2. archive.php

will show your all posts of specific category just you need to modify to fit your requirements. For more: https://codex.wordpress.org/Category_Templates

Upvotes: 2

Ajit Bohra
Ajit Bohra

Reputation: 373

I guess those topics on menu are links to category (You can added categories to menu). If yes then having category.php template file in your them will automatically list all the post from category and also set the page title to category

Upvotes: 0

Related Questions