WordPress.org

Forums

Custom Post Select (tagged post within a category) (4 posts)

  1. Fullish
    Member
    Posted 6 years ago #

    Hi,
    I would like to be able to do a query that selects all posts within a specificed category with the specified tags.

    Eg, post must be in category '1', and have tag 'Wordpress'.

    I've got this query that will select all posts within the specified category, category '1'.

    $querystr = "SELECT * FROM $wpdb->posts
    LEFT JOIN $wpdb->postmeta ON($wpdb->posts.ID = $wpdb->postmeta.post_id)
    LEFT JOIN $wpdb->term_relationships ON($wpdb->posts.ID = $wpdb->term_relationships.object_id)
    LEFT JOIN $wpdb->term_taxonomy ON($wpdb->term_relationships.term_taxonomy_id = $wpdb->term_taxonomy.term_taxonomy_id)
    WHERE $wpdb->term_taxonomy.term_id IN (1)
    AND $wpdb->term_taxonomy.taxonomy = 'category'
    AND $wpdb->posts.post_status = 'publish'
    ORDER BY $wpdb->posts.post_date DESC";

    And I've got this query that will select all the post with the tag 'Wordpress'

    $querystr = "SELECT * FROM $wpdb->posts
    LEFT JOIN $wpdb->postmeta ON($wpdb->posts.ID = $wpdb->postmeta.post_id)
    LEFT JOIN $wpdb->term_relationships ON($wpdb->posts.ID = $wpdb->term_relationships.object_id)
    LEFT JOIN $wpdb->term_taxonomy ON($wpdb->term_relationships.term_taxonomy_id = $wpdb->term_taxonomy.term_taxonomy_id)
    LEFT JOIN $wpdb->terms ON($wpdb->term_taxonomy.term_id = $wpdb->terms.term_id)
    WHERE $wpdb->terms.name = 'WordPress'
    AND $wpdb->term_taxonomy.taxonomy = 'post_tag'
    AND $wpdb->posts.post_status = 'publish'
    ORDER BY $wpdb->posts.post_date DESC";

    Except I can't seem to merge the two, can anyone give me any advice?
    Thanks

  2. Fullish
    Member
    Posted 6 years ago #

    bump, any help?

  3. Alexkoti
    Member
    Posted 6 years ago #

    Try this:

    $querystr = "SELECT * FROM $wpdb->posts
    LEFT JOIN $wpdb->postmeta ON($wpdb->posts.ID = $wpdb->postmeta.post_id)
    LEFT JOIN $wpdb->term_relationships ON($wpdb->posts.ID = $wpdb->term_relationships.object_id)
    LEFT JOIN $wpdb->term_taxonomy ON($wpdb->term_relationships.term_taxonomy_id = $wpdb->term_taxonomy.term_taxonomy_id)
    LEFT JOIN $wpdb->terms ON($wpdb->term_taxonomy.term_id = $wpdb->terms.term_id)
    
    WHERE ($wpdb->$wpdb->terms.term_id OR $wpdb->terms.name = 'WordPress')
    AND ($wpdb->term_taxonomy.taxonomy = 'category' OR $wpdb->term_taxonomy.taxonomy = 'post_tag')
    
    AND $wpdb->posts.post_status = 'publish'
    ORDER BY $wpdb->posts.post_date DESC";

    Use OR and parentheses to group them. Maybe you get the same results without filter by 'post_tag' or 'category'.

  4. nnanh01
    Member
    Posted 6 years ago #

    Hi everybody!

    How do I select posts except the ID that I knew??

    Or just select the post that have the ID I know??

    Pls help!

    Thanks!

Topic Closed

This topic has been closed to new replies.

About this Topic