First MovableType plugin

I've written my first MovableType plugin. It's nothing fancy, it just gets the count of all entries for a category and its children. Here's the code:
use strict;

use MT;
use MT::Template::Context;
MT::Template::Context->add_tag(CategoryTotalEntryCount 
           => \&category_entry_count );

sub category_entry_count {
    my($ctx) = @_;
    my $blog_id = $ctx->stash('blog_id');
    my $cat = $ctx->stash('category')
        or return $_[0]->error(MT->translate(
      "You used an [_1] tag outside of the proper context.",
      '<$MTCategoryCount$>' ));
    require MT::Entry;
    my %terms = ( blog_id => $blog_id, status => MT::Entry::RELEASE() );
    my %args;
    require MT::Placement;
    my @categories = _get_child_categories($cat);
    my $cat_entry_count = 0;
    for my $c (@categories) {
        $args{'join'} = [ 'MT::Placement', 'entry_id',
        { category_id => $c->id }, { unique => 1 } ];
        my @entries = MT::Entry->load(\%terms, \%args);
        $cat_entry_count+=scalar(@entries);
    }
    return $cat_entry_count;
}

sub _get_child_categories {
    my $c = shift;
    my @vals = ($c);
    if (scalar $c->children_categories) {
        for my $cat ($c->children_categories) {
            push(@vals,_get_child_categories($cat));
        }
    }
    return @vals;
}

I'm not the type of guy to be married to my code so questions and criticisms aren't met with a volume of invective.

Leave a comment

Close