Output attachments by category
-
I’ve been looking all over and can’t find any info that helps.
I’ve categorized my media and now I want to output a list of media based on a given category. I’d post code samples but nothing has helped so far it seems.
Thanks for your time!
-
Hello @madturki,
You can use WP_Query http://codex.ww.wp.xz.cn/Class_Reference/WP_Query#Taxonomy_Parameters
Or do you mean taxonomy archive page?
Nadia
Thanks Nadia,
I meant on the front end. For some reason no posts were being returned when I first tried get_posts. In the end this worked for me:
$args = array( 'post_type' => 'attachment', 'posts_per_page' => -1, 'post_status' =>'any', ); $attachments = new WP_Query($args); if ($attachments) { foreach ( $attachments->posts as $attachment ) { echo '<br>' . wp_get_attachment_url($attachment->ID) ; } }Thanks!
Sorry, no! This actually isn’t getting by category yet. If I enter in ‘category_name’ as an option I get nothing returned.
You have to study examples on this page http://codex.ww.wp.xz.cn/Class_Reference/WP_Query more carefully.
What you need is something like:
$args = array( 'post_type' => 'attachment', 'post_status' => 'any', 'tax_query' => array( array( 'taxonomy' => 'NAME_OF_YOUR_TAXONOMY', 'field' => 'slug', 'terms' => 'NAME_OF_THE_TERM_OF_YOUR_TAXONOMY' ) ) ); $the_query = new WP_Query( $args ); if ( $the_query->have_posts() ) { while ( $the_query->have_posts() ) { $the_query->the_post(); echo wp_get_attachment_image( get_the_ID(), 'full' ); } } else { // no attachments found } wp_reset_postdata();Hope it helps.
Nadia
The topic ‘Output attachments by category’ is closed to new replies.