0

I've added this function into my function.php file that allows me to specify images in my media library with categories.

/* Add Categories for Media Library Attachments
/*--------------------------------------------------*/

    // Add categories
    function add_categories_for_attachments() {
        register_taxonomy_for_object_type( 'category', 'attachment' );
    }
    add_action( 'init' , 'add_categories_for_attachments' );
    

I currently have a parent category and I am using it's child categories on my media library images. Example: Portfolio > Portraits, Weddings, Engagements. I am specifying these images with either portraits, weddings or engagements.

I also have a gallery page on my site dedicated to this group of images, and I am trying to retrieve the total count of all the media images that are being specified from the parent category "Portfolio".

I have done this with all my other archive/category pages with this code (although, these are ACTUAL posts):

/* The Function
/*--------------------------------------------------*/

function get_term_post_count( $taxonomy = 'category', $term = '', $args = [] )
{
    // Validate and sanitize our parameters, on failure, just return false
    if ( !$term )
        return false;

    if ( $term !== 'all' ) {
        if ( !is_array( $term ) ) {
            $term = filter_var(       $term, FILTER_VALIDATE_INT );
        } else {
            $term = filter_var_array( $term, FILTER_VALIDATE_INT );
        }
    }

    if ( $taxonomy !== 'category' ) {
        $taxonomy = filter_var( $taxonomy, FILTER_SANITIZE_STRING );
        if ( !taxonomy_exists( $taxonomy ) )
            return false;
    }

    if ( $args ) {
        if ( !is_array ) 
            return false;
    }

    // Now that we have come this far, lets continue and wrap it up
    // Set our default args
    $defaults = [
        'posts_per_page' => 1,
        'fields'         => 'ids'
    ];

    if ( $term !== 'all' ) {
        $defaults['tax_query'] = [
            [
                'taxonomy' => $taxonomy,
                'terms'    => $term
            ]
        ];
    }
    $combined_args = wp_parse_args( $args, $defaults );
    $q = new WP_Query( $combined_args );

    // Return the post count
    return $q->found_posts;
}


/* What goes into the HTML
/*--------------------------------------------------*/

<span><?php $count = get_term_post_count( 'category', '34' ); echo $count; ?> Posts found</span>

However, this code does not work for retrieving the count on media library images despite my category list listing the attachments as posts.

Any ideas on how I can get the total count for images from my library that are specified with my category "Portfolio" including it's children categories?

Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.