Adding posts to sidebar via category
-
This may be hard to follow so bear with me.
I want to add a section to my sidebar that will display only posts (not pages) from a specific category. What I’m trying to do here it setup something like a little spot for something like tweets or whatever we’re calling them these days.
I have a category setup called “Singles” and whenever I create a post and put it in that category, I want it to show up in the sidebar.
Any ideas on an easy way to do that without having to forgo the category thing and just go into the sidebar every single time and change it?
Thanks a lot.The page I need help with: [log in to see the link]
-
Using a Widget and Custom Query
You can use a Custom HTML or Text Widget in combination with a small amount of code to display posts dynamically.Steps:
- Go to Appearance > Widgets in your WordPress admin.
- Add a Text or Custom HTML widget to your sidebar.
- Paste the following PHP code inside your theme’s
functions.phpfile or a custom plugin (not directly in the widget):
function singles_category_posts() {
// Query to fetch posts from the "Singles" category
$args = array(
'category_name' => 'singles', // Slug of your category
'posts_per_page' => 5, // Number of posts to show
);
$query = new WP_Query($args);
if ($query->have_posts()) {
echo '<div class="singles-widget">';
echo '<h3>Latest Singles</h3>';
echo '<ul>';
while ($query->have_posts()) {
$query->the_post();
echo '<li><a href="' . get_permalink() . '">' . get_the_title() . '</a></li>';
}
echo '</ul>';
echo '</div>';
} else {
echo '<p>No singles yet!</p>';
}
wp_reset_postdata();
}Add the function output to your sidebar by embedding it in the widget like this:
<?php if (function_exists('singles_category_posts')) singles_category_posts(); ?>Using a Plugin for Dynamic Sidebar Content
If you’re not comfortable adding custom code, a plugin can help.Recommended Plugins:
- Display Posts – Post Listing Plugin
- Install and activate the plugin.
- Add a Text widget to your sidebar and use the following shortcode:shortcodeCopy code
[display-posts category="singles" posts_per_page="5"]
- Widget Logic
- Install the plugin.
- Use conditional tags to target your category in a widget.
Adding a Custom Sidebar File (Advanced)
If you’d like more control, you can directly edit your sidebar template (
sidebar.php) in your theme:- Open your theme’s
sidebar.phpfile. - Insert this code where you’d like the posts to appear:
<?php singles_category_posts(); ?>Let me know if you need help implementing this! 😊
Hello,
I hope your issue has been resolved. If not, please share the details with us, and we will check and provide you with a solution.Sorry. I haven’t had time to sit and look at this yet, some projects came up at my real job and have been taking all my time.
Once i get a chance I will try em and let you know.
The topic ‘Adding posts to sidebar via category’ is closed to new replies.