Get IDs of posts currently visible on archive

This probably is a easy one for many. And also probably is already answered here, but I don’t know how to search for it – so sorry I did search but not found anything.

I like to get the contents of all posts currently visible on a archive page, during wp_enqueue_scripts.

If I am right a good solution would be to just get_post_field('post_content', $post_id) for all of them.

So what I need is just the IDs for the posts that will be displayed on the current archive page. Something that involved new WP_Query or query_posts I guess, but that a area I never really touched.

1 Answer
1

When the wp_enqueue_scripts action fires, the main query has already run and the posts are in the global $wp_query. We just need to grab the ID from each object in $wp_query->posts, the wp_list_pluck function makes that easy:

function wpd_get_post_ids(){
    if( is_archive() ){
        global $wp_query;
        $post_ids = wp_list_pluck( $wp_query->posts, 'ID' );
        // $post_ids now contains an array of IDs
    }
}
add_action( 'wp_enqueue_scripts', 'wpd_get_post_ids' );

Leave a Comment