WordPress.org

Ready to get started?Download WordPress

Forums

get queried posts ID from loop (2 posts)

  1. slaaxy
    Member
    Posted 1 year ago #

    So I am writing a plugin that does some stuff and I have a widget that I place in my category template sidebar.

    I need that widget to get the ID of every queried posts from the main loop, but I am not sure how to go about that. I would assume I need to hook into the loop and for each loop collect the ID?

    The widget will then basically arrange the IDs in an array and create a button that links back to my plugin that takes these post ids and does some cool stuff. But I haven't figured out how to collect the id's from the current loop.

    so basically: How do I collect the Id's from the loop without editing the template? I need this to work on all loops that show more than one post, category, search result, homepage, everywhere.

    I have it working for single posts and regular categories, but for custom loops. For example querying multiple categories and terms, i have no idea how to do it.

  2. bcworkz
    Member
    Posted 1 year ago #

    The last query object is stored in the global $wp_query. You can get all the post objects in an array with $wp_query->posts. The post ID for each post object can be accessed as something like $post->ID, depending on how you process the array. Example to put all IDs into an array:

    global $wp_query;
    $id = array();
    $posts = $wp_query->posts;
    foreach ($posts as $post) {
      $id[] = $post->ID;
    }

Topic Closed

This topic has been closed to new replies.

About this Topic