0
votes

I'm looking for some help, for some reason this code isn't working when trying to display total image attachments on the main index.php page.

// Get all the attachments
$attachments = get_posts ( array(
'numberposts' => -1,
'post_type' => 'attachment',
'post_mime_type' => 'image',
'post_parent' => get_the_ID(),
'post_status' => 'inherit',
) );

// Count all the attachments
$total = count( $attachments );

The problem is, the loop is in the main index.php page, but it's calling a post.php template so I have placed this code there instead (I'm assuming that's still in the loop?) I am then calling $total just below it where I want to show "View all # images".

Any ideas why this is just displaying the number as 0 even though I have added an image gallery to the post using the basic Wordpress gallery media library?

Thanks

1
If you add print_r($attachments); is there anything printed to the page? - Howli
It actually seemed to have worked in the end. It seemed to be a problem with the images we were using to try and count. Thanks for your help. - jamhunn89

1 Answers

0
votes

The attachment count only increases if it's attached to a post. You can force the count by adding this:

$wp_taxonomies['category']->update_count_callback = '_update_generic_term_count';

in a function in your functions.php something like this:

function change_category_arg() {
    global $wp_taxonomies;
    if ( ! taxonomy_exists('category') )
        return false;

    $wp_taxonomies['category']->update_count_callback = '_update_generic_term_count';

}
add_action( 'init', 'change_category_arg' );

Explanation:

This is significant in the case of attachments. Because an attachment is a type of post, the default _update_post_term_count() will be used. However, this may be undesirable, because this will only count attachments that are actually attached to another post (like when you insert an image into a post). This means that attachments that you simply upload to WordPress using the Media Library, but do not actually attach to another post will not be counted. If your intention behind associating a taxonomy with attachments was to leverage the Media Library as a sort of Document Management solution, you are probably more interested in the counts of unattached Media items, than in those attached to posts. In this case, you should force the use of _update_generic_term_count() by setting '_update_generic_term_count' as the value for update_count_callback.

from Wordpress Codex on register_taxonomy