I found a function that allows me to attach a category to an image in media uploader

function add_categories_to_attachments() {
      register_taxonomy_for_object_type( 'category', 'attachment' );  
add_action( 'init' , 'add_categories_to_attachments' ); 

I'd like to be able to, when I'm in the category I assigned the image to, get the url of the image.

I just need to find out how to extract the info about the image associated with that category.

I should be able to do that via taxonomies, but I don't know how to achieve that.

EDIT: I forgot to add that I'm working outside of the loop, I need to show this image in the breadcrumbs of the category view.

1 Answer 1


I found what I needed:

$category = get_category( get_query_var( 'cat' ) );
$cat_id = $category->cat_ID;

$images = get_posts( array('post_type' => 'attachment', 'category__in' => $cat_id));

if ( !empty($images) ) {
    foreach ( $images as $image ) {
        $image_url = $image->guid;
} else{
    $image_url = '';

First I got the category, and current category ID I'm in. Then in $images I got the attachment that's attached to this category. Then I just listed them (I used print_r to see all the array values fro $images) and found the url (I need the url of the image to set the background image in the breadcrumbs). You can get the image directly by using wp_get_attachment_image($image->ID), but I need the url so I'm using this.

Oh and I'm avoiding the plugin usage, since I'm building a theme, and I'd like everything to be available from the theme itself.

Hope this helps someone :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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