WordPress.org

Ready to get started?Download WordPress

Forums

Looping over categories (3 posts)

  1. graemep
    Member
    Posted 8 years ago #

    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?

  2. skippy
    Member
    Posted 8 years ago #

    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.

  3. graemep
    Member
    Posted 8 years ago #

    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.

Topic Closed

This topic has been closed to new replies.

About this Topic

Tags