WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] Get all IDs from $wp_query (6 posts)

  1. v_decadence
    Member
    Posted 1 year ago #

    Hello!
    Is there anyway to get all matched posts IDs from $wp_query without looping it with calling the_post() function (I think it's to heavy operation for this task)?

    For example. I'm loading page of some category and need to get only IDs of the posts in current $wp_query.

  2. keesiemeijer
    moderator
    Posted 1 year ago #

    Try it with the fields parameter:
    http://codex.wordpress.org/Function_Reference/WP_Query#Return_Fields_Parameter
    Example:

    <?php
    // preserve the original query
    global $query_string;
    $the_query = new WP_Query( $query_string . '&fields=ids' );
    if(isset($the_query->posts) && !empty($the_query->posts)){
    	foreach((array) $the_query->posts as $id) {
    		echo $id;
    	}
    }
    ?>

    If you need the ids from a specific query you can also use get_posts:

    <?php
    // get 10 recent post IDs from category 1
    $the_query = get_posts( 'cat=1&posts_per_page=10&fields=ids' );
    if($the_query){
    	foreach($the_query as $id) {
    		echo $id;
    	}
    }
    ?>
  3. v_decadence
    Member
    Posted 1 year ago #

    keesiemeijer, thanks for the quick reply!
    This is exactly what I needed.
    But now I have another question - what are possible values of "fields" option?

    In docs it is:
    'ids' - Return an array of post IDs.
    'id=>parent' - Return an associative array [ parent => ID, … ].
    any other value or empty (default): return an array of post objects

    I don't understand the second and third options - which keys/values are supported and why are they reversed - id=>parent then parent => ID?
    And "any other value or empty" - value of what?

  4. keesiemeijer
    moderator
    Posted 1 year ago #

    The second option will return all parent (page) ID's:

    $args = array('fields' => 'id=>post_status');
    $the_query = get_posts( $args );
    // $the_query returns all parent post IDs

    All other values will return full post objects. Only 'ids' and 'id=>parent' is supported for now. the output for the parent post IDs is an array like:

    [posts] => Array
            (
                [0] => stdClass Object
                    (
                        [ID] => 25
                        [post_parent] => 21
                    )
    
                [1] => stdClass Object
                    (
                        [ID] => 32
                        [post_parent] => 0
                    )
            )
  5. v_decadence
    Member
    Posted 1 year ago #

    I understood. Thank you very much!

  6. keesiemeijer
    moderator
    Posted 1 year ago #

    You're welcome. I'm glad you've got it resolved :-)

Topic Closed

This topic has been closed to new replies.

About this Topic

Tags