Correct Way To Show Custom Taxonomy for Image Attachments on Template File

I’ve created a custom taxonomy called imagetags using the following code:

// Register Custom Taxonomy
function custom_imagetags_taxonomy()  {
$labels = array(
'name'                       => _x( 'Image Tags', 'Taxonomy General Name', 'text_domain' ),
'singular_name'              => _x( 'Image Tag', 'Taxonomy Singular Name', 'text_domain' ),
'menu_name'                  => __( 'Image Tags', 'text_domain' ),
'all_items'                  => __( 'All Image Tags', 'text_domain' ),
'parent_item'                => __( 'Parent Image Tag', 'text_domain' ),
'parent_item_colon'          => __( 'Parent Image Tag:', 'text_domain' ),
'new_item_name'              => __( 'New Image Tag', 'text_domain' ),
'add_new_item'               => __( 'Add New Image Tag', 'text_domain' ),
'edit_item'                  => __( 'Edit Image Tag', 'text_domain' ),
'update_item'                => __( 'Update Image Tag', 'text_domain' ),
'separate_items_with_commas' => __( 'Separate Image Tags with Commas', 'text_domain' ),
'search_items'               => __( 'Search Image Tags', 'text_domain' ),
'add_or_remove_items'        => __( 'Add or Remove Image Tags', 'text_domain' ),
'choose_from_most_used'      => __( 'Choose From Popular Image Tags', 'text_domain' ),
);

$rewrite = array(
'slug'                       => 'imagetags',
'with_front'                 => true,
'hierarchical'               => false,
);

$args = array(
'labels'                     => $labels,
'hierarchical'               => false,
'public'                     => true,
'show_ui'                    => true,
'show_admin_column'          => true,
'show_in_nav_menus'          => true,
'show_tagcloud'              => true,
'rewrite'                    => $rewrite,
);

register_taxonomy( 'imagetags', 'attachment', $args );
}

// Hook into the 'init' action
add_action( 'init', 'custom_imagetags_taxonomy', 0 );

Now I’m trying to create a template page to show images that fit a particular imagetag.

Read More

I started by naming a file taxonomy-imagetags.php

I’m stuck on the type of loop to use.

I’ve tried a few and nothing has worked.

Would appreciate any help.

Related posts

Leave a Reply

2 comments

  1. The issue is with the post_status argument of the default query generated for your taxonomy terms. If you change the status via the pre_get_posts action to inherit or any, you can get attachments to show up.

    however– is this the correct way to do this- I honestly don’t know. This will show attachments to posts that are drafts, and maybe private. I haven’t tested it thoroughly so beware.

    Perhaps someone else can chime in with more knowledge and info.

    function wpa82573_show_tax_attachments( $query ) {
        if ( $query->is_tax('imagetags') && $query->is_main_query() ) {
            $query->set( 'post_status', 'inherit' );
        }
    }
    add_action( 'pre_get_posts', 'wpa82573_show_tax_attachments' );