• Resolved sam_m

    (@sam_m)


    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

Viewing 3 replies - 1 through 3 (of 3 total)
  • Moderator Samuel Wood (Otto)

    (@otto42)

    WordPress.org Admin

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

    Thread Starter sam_m

    (@sam_m)

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

    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!

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘SQL Query to retrieve posts by category’ is closed to new replies.