Function Reference/Wp Get Object Terms

How can I use wp_get_object_terms() lớn get a danh mục of all the terms attached khổng lồ all posts in the current query?

For example, for the current query I want to get an array of the terms from the "Alfa" taxonomy that are contained in all the queried posts.

Bạn đang xem: Function reference/wp get object terms

wp_get_object_terms($wp_query, "alfa");But that only seems lớn be returning one công trình in the array...

I am doing this khổng lồ build an array khổng lồ cross check one taxonomy with another for a navigation thực đơn, & am currently doing this with the following code but I think there must be a better way.

Xem thêm: Công Nghệ Xml Và Ứng Dụng Xml, Tài Liệu Công Nghệ Xml Và Ứng Dụng

Please help! Thanks!

$queried_terms = array();if ( $wp_query->have_posts() ) : while ( $wp_query->have_posts() ) : $wp_query->the_post(); $postid = $post->ID; if( has_term( "", "alfa", $postid) ) $terms = get_the_terms( $postid, "alfa" ); foreach($terms as $term) $queried_terms<> = $term->slug; endwhile; endif;rewind_posts();wp_reset_query();$queried_terms = array_unique($queried_terms);
multi-taxonomy-query advanced-taxonomy-queries terms
Improve sầu this question
edited Apr 26 "12 at 3:00
asked Apr 26 "12 at 0:52

39111 gold badge33 silver badges1616 bronze badges
Add a phản hồi |

2 Answers 2

Active sầu Oldest Votes
I think you"re on the right traông chồng because wp_get_object_terms() can take an array of IDs for its first argument, it"s just that $wp_query is not the array you want.

I can"t guarantee that this is more efficient (not my area of expertise), but I believe this snippet would vày what you want with at least one fewer loop and no array_unique():

// get $wp_queryglobal $wp_query;// get array of post objects $my_posts = $wp_query -> posts;// make array for the post IDs$my_post_ids = array();// loop through posts array for IDsforeach( $my_posts as $my_post ) $my_post_ids<> = $my_post->ID;// get the terms$my_terms = wp_get_object_terms( $my_post_ids, "alfa" );wp_get_object_terms() takes a 3rd $args parameter which you may need to lớn phối to lớn get the ouput you want, but I"ll leave that to you.

UPDATE:This can be even shorter using the new-to-me function wp_list_pluck(). Again this is untested but looks right:

// get $wp_queryglobal $wp_query;// get array of post objects $my_posts = $wp_query -> posts;// NEW: make array of the post IDs in one step$my_post_ids = wp_list_pluck( $my_posts, "ID" );// get the terms$my_terms = wp_get_object_terms( $my_post_ids, "alfa" );You can see in the source that this runs the same foreach loops code, but it looks a little nicer.

tinh dầu vape, pod 1 lần