• Resolved v_decadence

    (@v_decadence)


    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.

Viewing 5 replies - 1 through 5 (of 5 total)
  • Moderator keesiemeijer

    (@keesiemeijer)

    Try it with the fields parameter:
    https://codex.www.ads-software.com/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;
    	}
    }
    ?>

    Thread Starter v_decadence

    (@v_decadence)

    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?

    Moderator keesiemeijer

    (@keesiemeijer)

    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
                    )
            )

    Thread Starter v_decadence

    (@v_decadence)

    I understood. Thank you very much!

    Moderator keesiemeijer

    (@keesiemeijer)

    You’re welcome. I’m glad you’ve got it resolved ??

Viewing 5 replies - 1 through 5 (of 5 total)
  • The topic ‘Get all IDs from $wp_query’ is closed to new replies.