Skip to content

Instantly share code, notes, and snippets.

@stnc
Last active August 12, 2024 02:14
Show Gist options
  • Save stnc/d0b02be3dd52d31fed0173d232f8fd39 to your computer and use it in GitHub Desktop.
Save stnc/d0b02be3dd52d31fed0173d232f8fd39 to your computer and use it in GitHub Desktop.
Get all categories and posts in those categories
<?php
//https://wordpress.stackexchange.com/questions/43426/get-all-categories-and-posts-in-those-categories
$args = array(
'posts_per_page' => -1
);
$query = new WP_Query($args);
$q = array();
while ( $query->have_posts() ) {
$query->the_post();
$a = '<a href="'. get_permalink() .'">' . get_the_title() .'</a>';
$categories = get_the_category();
foreach ( $categories as $key=>$category ) {
$b = '<a href="' . get_category_link( $category ) . '">' . $category->name . '</a>';
}
$q[$b][] = $a; // Create an array with the category names and post titles
}
/* Restore original Post Data */
wp_reset_postdata();
foreach ($q as $key=>$values) {
echo $key;
echo '<ul>';
foreach ($values as $value){
echo '<li>' . $value . '</li>';
}
echo '</ul>';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment