[resolved] SQL Query to retrieve posts by category (4 posts)

  1. sam_m
    Posted 8 years ago #

    Hi, being new to WordPress, can someone please help me with a query I need to retrieve posts belonging to a specifc category or categories as supplied by an argument from a widget ...

    This is the code I have currently, where $includecats is the categories to include and $show is the number of posts to list..

    $posts = $wpdb->get_results("SELECT DISTINCT * FROM $wpdb->posts
    INNER JOIN $wpdb->term_relationships ON $wpdb->posts.ID = $wpdb->term_relationships.object_id
    INNER JOIN $wpdb->term_taxonomy
    ON $wpdb->term_relationships.term_taxonomy_id = $wpdb->term_taxonomy.term_taxonomy_id
    WHERE $wpdb->term_taxonomy.term_id = '$includecats' AND post_type='post' AND post_date < NOW( ) AND post_status = 'publish' ORDER BY post_date DESC LIMIT $show");

    The result I get is two posts duplicated and one posts that has is not categorised under the category I am trying to retrieve but has a tag in the post.

    Any help will be highly appreciated. Thx

  2. Why not use get_posts, or write your own Loop? Why use SQL directly?

  3. sam_m
    Posted 8 years ago #

    Thx Otto. I found a plugin to help me do it.

  4. Modifiedcontent
    Posted 7 years ago #

    I use a modified version of WordPress in another site - I needed a flexible category system like WordPress has.

    The "items" in my system are not regular posts and I need them outside WordPress, so any pointers on what these queries would look like are very much appreciated!

Topic Closed

This topic has been closed to new replies.

About this Topic