Get IDs of posts currently visible on archive
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' );