sort_method モディファイア(その2)
Movable Type で、カテゴリやフォルダを並べ替えるための sort_method モディファイアの紹介です。「sort_method モディファイア(その1)」の続きです。
1.ソート条件に対応するプラグインの作成
指定した条件に対応するプラグインを作成します。ここでは「sort_method モディファイア(その1)」で紹介したソースコードを利用します。パッケージ名は少し変えてますが、次の2ファイルを作成します。
config.yaml
id: CategorySorting
name: CategorySorting
CategorySorting.pm
package CategorySorting;
my %category_priorities = (
'foo' => 1,
'bar' => 2,
);
sub cat_sort ($$) {
my ($a, $b) = @_;
my $a_pri = $category_priorities{$a->label} || 1000;
my $b_pri = $category_priorities{$b->label} || 1000;
unless ($a_pri == 1000 && $b_pri == 1000) {
return $a_pri <=> $b_pri;
}
return $a->label cmp $b->label;
}
ハッシュ変数 %category_priorities にカテゴリの優先度を設定します。このプラグインではカテゴリ名をソート条件にしており、「foo」というカテゴリを1番目に、「bar」というカテゴリを2番目に並ぶように、優先度を設定しています。
変数 $a と $b には、ソート対象のカテゴリオブジェクトが設定されます。ソートするカテゴリの優先度がハッシュ変数%category_prioritiesに設定されていれば、2つのカテゴリのソート結果を返却し、そうでない場合は直接カテゴリ名でのソート結果を返却します。
プラグイン作成後、次のようなディレクトリ構成になるように plugins ディレクトリに2つのファイルをアップロードします。
plugins/
CategorySorting/
config.yaml
lib/
CategorySorting.pm
システム管理画面の「ツール」→「プラグイン」で「CategorySorting」が表示されればOKです。
2.sort_method モディファイアの追加
MTTopLevelCategories タグなどに、sort_method モディファイアを追加し、ソートする条件を指定します。ここではソート条件として、作成したプラグインのメソッド名を指定します。
<mt:IfArchiveTypeEnabled archive_type="Category">
<div class="widget-archive widget-archive-category widget">
<h3 class="widget-header">カテゴリ</h3>
<div class="widget-content">
<mt:TopLevelCategories sort_method="CategorySorting::cat_sort">
<mt:SubCatIsFirst>
<ul>
</mt:SubCatIsFirst>
<mt:If tag="CategoryCount">
<li><a href="<$mt:CategoryArchiveLink$>"<mt:If tag="CategoryDescription"> title="<$mt:CategoryDescription remove_html="1" encode_html="1"$>"</mt:If>><$mt:CategoryLabel$> (<$mt:CategoryCount$>)</a>
<mt:Else>
<li><$mt:CategoryLabel$>
</mt:If>
<$mt:SubCatsRecurse$>
</li>
<mt:SubCatIsLast>
</ul>
</mt:SubCatIsLast>
</mt:TopLevelCategories>
</div>
</div>
</mt:IfArchiveTypeEnabled>
ソート条件は各階層単位に適用されます。
sort_method モディファイア(その1)
Movable Type の MTSubCategories タグや MTTopLevelCategories タグでは sort_method というカテゴリを並び替えるモディファイアが利用可能です。
ネットで情報を検索すると、sort_method のサンプルで大体同じソースコードが登場するのですが、発信元は David Raynes 氏の SubCategories プラグインのようです。
また、よくみかけるソースコードは以下にありました。
SubCategories Plugin Documentation
package rayners::CategorySorting;
my %category_priorities = (
# I want 'MT Plugins' to appear before 'MT Brainstorming'
# followed by the rest
'MT Plugins' => 1
'MT Brainstorming' => 2,
# And I want 'SubCategories' to be the first plugin listed,
# followed by 'Entry' and then the rest of the plugins
'SubCategories' => 1,
'Entry' => 2,
);
sub cat_sort ($$) {
my ($a, $b) = @_;
my $a_pri = $category_priorities{$a->label} || 1000;
my $b_pri = $category_priorities{$b->label} || 1000;
unless ($a_pri == 1000 && $b_pri == 1000) {
# At least one of them has a defined priority
# so sort on that
return $a_pri <=> $b_pri;
}
# Both are the default value (1000)
# so sort alphabetically
return $a->label cmp $b->label;
}