Is there a way to get the results of a loop with a filter before the code for the loop is performed in the structure of your code?

My markup is something like this:

   /* can I use a function to get the results from a loop performed after this point with a filter or hook of some sort */
    /* a loop/foreach etc. with results I would also like information for above */

or would I need to duplicate the loop/foreach or restructure the page to achieve this?

  • this isn't very clear - what results do you want to get? – anu Jul 18 '12 at 7:45
  • I have a custom post type (programme) that I'm already looping through that have a custom taxonomy (show) - the custom taxonomy (show) is used to check if another custom post type (twitter hashtag) exists, if it does I need to grab the hashtag before the loop. – erichmond Jul 18 '12 at 7:56

@Rutwick's answer was what I thought when I read the title, but I think you're just wanting to use get_the_terms() which can be out of the loop like this:

$my_post_terms = get_the_terms( $post->ID, 'show' );
if( $my_post_terms && !is_wp_error( $my_post_terms ) ) {
    // do something here with $my_post_terms array
| improve this answer | |
  • This is more like it but, I only want the terms from the post id's of the loop lower down the page :-s My hack at the moment is to repeat the loop again at the top as well. Hmm, unless I only have it at the top - the foreach should still work lower down the page I guess... need to test that... – erichmond Jul 19 '12 at 5:30
  • Without seeing your full code, you can't expect any of us to give you answers specific to it. I would not guess that you had two loops based on your question. Maybe you need rewind_posts() to just let you run the loop twice. – mrwweb Jul 19 '12 at 15:40
  • resolved with your original suggestion anyway thanks – erichmond Jul 26 '12 at 12:59

Try using pre_get_posts. The query is available as a parameter to this filter. [Codex]

| improve this answer | |
  • Not sure that will work as in some cases I'm using get_posts then iterating foreach function, or will it work for that to if I do it in a different way? – erichmond Jul 18 '12 at 19:48
  • You can use it on get_posts as well. Just add that action right before the get_posts call, and remove it after the call. – Rutwick Gangurde Jul 19 '12 at 5:45
  • And the same for WP_Query? I presume I would need to change the $query variable to my chosen variable eg if '$my_query new WP_Query' then I would need to change the variable to '$my_query' passed to the function? – erichmond Jul 19 '12 at 6:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.