Last active
August 12, 2024 02:14
-
-
Save stnc/d0b02be3dd52d31fed0173d232f8fd39 to your computer and use it in GitHub Desktop.
Get all categories and posts in those categories
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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