Reputation: 37
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
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
category.php
orarchive.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
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