MTAppjQuery で選択されたカテゴリによって、複数あるアイテムフィールドのアップロード先ディレクトリを変更する方法をご紹介します。
今日は MTAppjQuery を利用したカスタマイズとして、 記事に設定した複数のアセット系フィールドについて、選択されたカテゴリによって、それぞれのフィールドのアップロード先ディレクトリを変更する方法をご紹介します。
例として下記のような3つのコンテンツフィールドを作成します。
カテゴリを作成
次に下記のような3つのカテゴリを作成します。
下記のコードを user.js に追記します。コードの内容はコード中にコメントとして書き込みました。
(function($){
'use strict';
// 記事に限定
if (mtappVars.screen_id === 'edit-entry') {
// リンクボタンにパラメーを追加するための jQuery プラグイン
$.fn.MTAppAddExtraPath = function(options){
const op = $.extend({
value: ''
}, options);
if (op.value === '') {
return;
}
return this.each(function(){
let href = $(this).attr('href');
if (!href) {
return;
}
href = href.replace(/&extra_path=[^&]*/gi, '');
href += ('&extra_path=' + op.value);
$(this).attr('href', href);
});
};
// END リンクボタンにパラメーを追加するための jQuery プラグイン
// MTAppInCats で選択されたカテゴリごとに処理を変える
$.MTAppInCats({
categories: null,
code: function(categories){
// entry_category_01(ID: 9)が選択された場合
if ($.inArray('9', categories) !== -1) {
// アセットフィールド
$('#customfield_asset01-field a.mt-open-dialog').MTAppAddExtraPath({
value: 'files/cat01'
});
// 画像フィールド
$('#customfield_image01-field a.mt-open-dialog').MTAppAddExtraPath({
value: 'images/cat01'
});
// ビデオフィールド
$('#customfield_video01-field a.mt-open-dialog').MTAppAddExtraPath({
value: 'videos/cat01'
});
}
// entry_category_02(ID: 10)が選択された場合
else if ($.inArray('10', categories) !== -1) {
// アセットフィールド
$('#customfield_asset01-field a.mt-open-dialog').MTAppAddExtraPath({
value: 'files/cat02'
});
// 画像フィールド
$('#customfield_image01-field a.mt-open-dialog').MTAppAddExtraPath({
value: 'images/cat02'
});
// ビデオフィールド
$('#customfield_video01-field a.mt-open-dialog').MTAppAddExtraPath({
value: 'videos/cat02'
});
}
// entry_category_03(ID: 11)が選択された場合
else if ($.inArray('11', categories) !== -1) {
// アセットフィールド
$('#customfield_asset01-field a.mt-open-dialog').MTAppAddExtraPath({
value: 'files/cat03'
});
// 画像フィールド
$('#customfield_image01-field a.mt-open-dialog').MTAppAddExtraPath({
value: 'images/cat03'
});
// ビデオフィールド
$('#customfield_video01-field a.mt-open-dialog').MTAppAddExtraPath({
value: 'videos/cat03'
});
}
}
});
// END MTAppInCats で選択されたカテゴリごとに処理を変える
}
// END 記事に限定
// アセットのダイアログ内で下記のコードを実行する
if (mtappVars.params.dialog) {
// 上段のコードでセットした extra_path を取得
const extraPath = mtappVars.params.extra_path || '';
if (extraPath) {
$('#extra_path').val(extraPath);
}
}
// END アセットのダイアログ内で下記のコードを実行する
})(jQuery);
これで下図のようにフィールドごとに、かつ選択されたカテゴリにごとに別のアップロード先ディレクトリがセットされました。