Add Snippet To Project
Have you ever wanted to display a select list of posts related to each category on your WordPress website? Being able to do so not only improves navigation but also enhances the user experience by offering relevant content. This tutorial will guide you through the steps to create a custom list of posts for each category on your WordPress site. Let’s delve in and customize the way how your internet audience interfaces with your content.
function wpturbo_list_posts_per_category() {
$categories = get_categories();
foreach ( $categories as $category ) {
$posts = get_posts( array( 'category' => $category->term_id ) );
echo '<h2>' . $category->name . '</h2>';
echo '<ul>';
foreach ( $posts as $post ) {
echo '<li>' . get_the_title( $post->ID ) . '</li>';
}
echo '</ul>';
}
}
add_shortcode( 'wpturbo_list_posts_per_category', 'wpturbo_list_posts_per_category' );
Our function, wpturbo_list_posts_per_category()
, begins by fetching an array of all categories using the get_categories()
function. This function returns an array of objects where each object represents a category.
We then loop through each category object in the array using a foreach
loop. For each category, we get the ID and use it to fetch all posts in that category.
Using the get_posts
function, we specify the ‘category’ field to be equal to our category’s term_id, meaning it will only return posts within that particular category. The get_posts
function returns an array of post objects.
Next, we print out the category’s name using echo
, contained within <h2>
HTML tags to represent it as a heading. We follow this by outputting an opening <ul>
tag as we’re about to list the posts in this category.
Another foreach
loop cycles through each post object in the array. For each post, we retrieve and print out the title with the get_the_title()
function, passing in the post’s ID ($post->ID
). The title is wrapped in <li>
HTML tags indicating it as an item within our list.
Once all the post titles have been printed, we echo out a closing </ul>
tag, signifying the end of our list for that category.
Finally, we use the add_shortcode
function to create a shortcode [wpturbo_list_posts_per_category]
that executes our wpturbo_list_posts_per_category()
function when used in posts, pages, or widgets.
Thus, this function, embedded in a shortcode, allows you to output a list of posts for each category in a highly user-friendly and visually organized format right within your WordPress site.