アルファサード株式会社 代表取締役 野田 純生のブログ


同一カテゴリーの前後のエントリーを出力するPreviousNextInCategory互換プラグイン。


公開日 : 2008-08-10 11:45:40


1,000ページ程のブログの再構築で500エラーが出るってんで原因を探していてPreviousNextInCategoryプラグインが怪しいっぽかったので同様の動作をしてより軽量(? 高速?) なものを作成しました。

おそらく500エラーになったのは以下のエントリーと同じ理由と思われます。

プラグインは2種類あります。4.1のコードを眺めていて「$terms->{by_category} = 1;」ってのが使えんの!? で使ったらいけたんだけど、4.2rc2でエラーが出てしまってあら残念。仕様変更でなくてバグだったらいいなぁ、と思いつつちょっと最新のベータとかで試せてなくてまぁ両方晒しておきます。

4.1で使える版の該当部分のコード。シンプルで書きやすくて素敵。残念ながら4.2rc2ではエラーに。

sub _hdlr_entry_nextprev {
    my( $meth, $ctx, $args, $cond ) = @_;
    my $e = $ctx->stash('entry')
        or return $ctx->_no_entry_error($ctx->stash('tag'));
    my $terms = { status => MT::Entry::RELEASE() };
    $terms->{by_category} = 1 ;
    my $entry = $e->$meth($terms);
    my $res = '';
    if ($entry) {
        my $builder = $ctx->stash('builder');
        local $ctx->{__stash}->{entry} = $entry;
        local $ctx->{current_timestamp} = $entry->authored_on;
        my $out = $builder->build($ctx, $ctx->stash('tokens'), $cond);
        return $ctx->error( $builder->errstr ) unless defined $out;
        $res .= $out;
    }
    $res;
}

4.2でも問題なく動くコードはこちら。制限として、タイムスタンプが全く同一の場合はうまくいかないっていうのがあります。割り切って使えるならこれでもいいか。

sub _hdlr_entry_nextprev {
    my( $meth, $ctx, $args, $cond ) = @_;
    my $e = $ctx->stash('entry')
        or return $ctx->_no_entry_error($ctx->stash('tag'));
    my $category_id;
    if (my $c = $e->category) {
        $category_id = $c->id;
    }
    return '' unless $category_id;
    my $entry = _hdlr_neighbor_entry( $e, $category_id, $meth );
    my $res = '';
    if ( $entry ) {
        my $builder = $ctx->stash('builder');
        local $ctx->{__stash}->{entry} = $entry;
        local $ctx->{current_timestamp} = $entry->authored_on;
        my $out = $builder->build($ctx, $ctx->stash('tokens'), $cond);
        return $ctx->error( $builder->errstr ) unless defined $out;
        $res .= $out;
    }
    $res;
}

sub _hdlr_neighbor_entry {
    my ( $entry, $category_id, $meth ) = @_;
    my $direction = 'ascend';
    if ( $meth eq 'previous' ) {
        $direction = 'descend';
    }
    return MT::Entry->load({ blog_id => $entry->blog_id,
                             status => MT::Entry::RELEASE() },
                           { sort => "authored_on",
                             start_val => $entry->authored_on,
                             direction => $direction,
                             limit => 1,
                             'join' => [ 'MT::Placement', 'entry_id',
                                       { blog_id => $entry->blog_id,
                                         category_id => $category_id },
                                       { unique => 1 } ],
                           } );
}

ダウンロード

テンプレートタグの記述はPreviousNextInCategoryプラグインと同じです。



このブログを書いている人
野田純生の写真
野田 純生 (のだ すみお)

大阪府出身。ウェブアクセシビリティエバンジェリスト。 アルファサード株式会社の代表取締役社長であり、現役のプログラマ。経営理念は「テクノロジーによって顧客とパートナーに寄り添い、ウェブを良くする」。 プロフィール詳細へ