The suggested code needs to be integrated into your theme’s template used to display the post list. The key element is where a category header is output when the current post’s category does not match the previous post’s category. I mean this part and the 3 lines after it: if($current_taxonomy != $current_tax_terms) {
. You also need the parts where those variables get assigned values. For other elements, you’ll want to use the code from your theme so its styling gets properly applied.
WP does not have a built in way to order posts by category name, so a custom SQL query would need to be created, or you could expend a lot of effort through filtering to get WP_Query to work the way you want.
I don’t know what request you want used to get this list in return. One solution is to create a page for the purpose and utilize a custom page template to make the SQL query and display the results. You can start with your theme’s page.php or index.php template as a starting point, but in making a SQL query through the global $wpdb object, you wouldn’t use the usual while (have_posts()):
loop structure. Instead just foreach
through the returned results. A query through $wpdb which orders posts by category looks something like this:
global $wpdb;
$query = $wpdb->get_results( "SELECT * FROM $wpdb->posts AS p
LEFT JOIN $wpdb->term_relationships AS r ON (p.ID = r.object_id)
INNER JOIN $wpdb->term_taxonomy AS x ON (r.term_taxonomy_id = x.term_taxonomy_id)
INNER JOIN $wpdb->terms AS t ON (r.term_taxonomy_id = t.term_id)
WHERE p.post_type = 'post'
AND p.post_status = 'publish'
AND x.taxonomy = 'category'
ORDER BY t.name ASC, p.post_date DESC;"
);