Title: Looping over categories
Last modified: August 18, 2016

---

# Looping over categories

 *  [graemep](https://wordpress.org/support/users/graemep/)
 * (@graemep)
 * [21 years ago](https://wordpress.org/support/topic/looping-over-categories/)
 * In order to produce an index page of posts by category I did the following in
   the home.php file of my theme:
 * I query the database like so:
 * `$wpdb->get_results("SELECT DISTINCT cat_name,cat_ID,category_nicename FROM $
   wpdb->categories, $wpdb->post2cat WHERE $wpdb->categories.cat_ID = $wpdb->post2cat.
   category_id ORDER BY cat_name ASC");`
 * and then did a foreach loop over the result. I then
    1) call query_posts 2) run
   The Loop on each iteration of the foreach loop.
 * This works, what I want to know is if this is a stable, efficient and generally
   sensible way of doing it. I did get a MySQL error 28 but I gather than is probably
   the hosts fault, should I expect any other problems or should I be comfortable
   with this?

Viewing 2 replies - 1 through 2 (of 2 total)

 *  [skippy](https://wordpress.org/support/users/skippy/)
 * (@skippy)
 * [21 years ago](https://wordpress.org/support/topic/looping-over-categories/#post-220427)
 * You’re fetching _all_ the posts in your database doing this. If you’re only showing
   X number of posts per category, you could put a `LIMIT` clause in your initial
   query, to reduce the amount of work the database does.
 *  Thread Starter [graemep](https://wordpress.org/support/users/graemep/)
 * (@graemep)
 * [21 years ago](https://wordpress.org/support/topic/looping-over-categories/#post-220531)
 * Thanks skippy, unfortunately I do need all the posts and categories (at least
   for the moment).
 * Since I posted the above it occured to me that maybe I should lose the WHERE 
   clause and, instead, test for empty cats after each time I rerun query posts.

Viewing 2 replies - 1 through 2 (of 2 total)

The topic ‘Looping over categories’ is closed to new replies.

## Tags

 * [loop](https://wordpress.org/support/topic-tag/loop/)
 * [MySQL](https://wordpress.org/support/topic-tag/mysql/)

 * 2 replies
 * 2 participants
 * Last reply from: [graemep](https://wordpress.org/support/users/graemep/)
 * Last activity: [21 years ago](https://wordpress.org/support/topic/looping-over-categories/#post-220531)
 * Status: not resolved

## Topics

### Topics with no replies

### Non-support topics

### Resolved topics

### Unresolved topics

### All topics
