WordPress.org

Ready to get started?Download WordPress

Forums

Retrieve just Post IDs from multiple categories (2 posts)

  1. Maxaud
    Member
    Posted 3 years ago #

    I'm trying to get a list of post IDs from multiple categories and I'm dealing with thousands of posts per category so I don't want to get the whole post object when all I need is the post's ID.

    Anyone know of a way to return just just the IDs of posts instead of the whole post object?

    (Sort of like get_posts() but all I need is the ID's returned)

  2. Maxaud
    Member
    Posted 3 years ago #

    Was able to come up with something that works for me.
    Replace 1,5,7 with the category IDs that you're searching for posts under.

    <?php
    $query = "
    	SELECT p.ID FROM $wpdb->posts p
    	JOIN $wpdb->term_relationships tr ON (p.ID = tr.object_id)
    	JOIN $wpdb->term_taxonomy tt ON (tr.term_taxonomy_id = tt.term_taxonomy_id)
    	JOIN $wpdb->terms t ON (tt.term_id = t.term_id)
    	WHERE tt.taxonomy = 'category' AND t.term_id IN ('1,5,7')
    ";
    
    $post_ids = $wpdb->get_col($wpdb->prepare($query));
    ?>

    Note: it returns an array of posts IDs like so (1 & 6 are IDs):

    Array
    (
        [0] => 1
        [1] => 6
    )

Topic Closed

This topic has been closed to new replies.

About this Topic