Kareen Lagasca
Kareen Lagasca

Reputation: 939

How to display the Images (from Media Library) under a specific Category in Wordpress?

So I have this function code that adds "Category" to the Images that I upload in my Wordpress website.

/** Register taxonomy for images */
function olab_register_taxonomy_for_images() {
    register_taxonomy_for_object_type( 'category', 'attachment' );
}
add_action( 'init', 'olab_register_taxonomy_for_images' );

/** Add a category filter to images */
function olab_add_image_category_filter() {
    $screen = get_current_screen();
    if ( 'upload' == $screen->id ) {
        $dropdown_options = array( 'show_option_all' => __( 'View all categories', 'olab' ), 'hide_empty' => false, 'hierarchical' => true, 'orderby' => 'name', );
        wp_dropdown_categories( $dropdown_options );
    }
}
add_action( 'restrict_manage_posts', 'olab_add_image_category_filter' );

enter image description here

I'd like to know how can I call or display all the Images that falls under a specific category (the category number that I want to call is Category # 2190)?

What I'm trying to do here is to have a photo gallery that showcases all the photos i've uploaded and tagged under the category #2190 - "Photo of the day"?

Upvotes: 6

Views: 3106

Answers (1)

Anand Shah
Anand Shah

Reputation: 14913

The following code should do what you are trying to achieve

<?php
$images = get_posts( array('post_type' => 'attachment', 'category__in' => array(2190))  );
if ( !empty($images) ) {
    foreach ( $images as $image ) {
        echo wp_get_attachment_image($image->ID).'<br />';
        echo $image->post_title .'<br />';
        the_attachment_link( $image->ID, true );
    }
}
?>

Upvotes: 4

Related Questions