LoginSignup
5
4

More than 5 years have passed since last update.

Movable Typeでカスタムフィールドで表示するNew画像を2週間のみ表示させる方法

Last updated at Posted at 2014-11-20

New画像を特定の期間だけ表示させるということはよくあります。
今回もそれと同じような要件があったので、記事にまとめてみました。
現在は、プラグインなどが豊富に揃っていますが、案件によって入れれない場合もあるのでメモしておきたいと思いました。

  • 実装したMTのバージョンは5.02

一定時間で自動的に消える New マークを付ける JavaScript の jQuery 版の「newmark_jquery.js」を使って実装してみました。

要件

  • カスタムフィールドでNewを表示させる
  • Newボタンは、14日後に自動的に非表示
  • Newのカスタムフィールド(チェックボックス)がなかったら表示しない

ソース

HTMLには、カスタムフィールドで囲ったアイコン部分とJSのループで回すためのクラスを入れました。

<mt:If tag="item_new"><p class="mod-new" title="<$mt:EntryDate format="%Y年%m月%d日 %H時%M分%S秒"$>"></p></mt:If>

JS側には、.mod-newの値を拾いループさせています。 
この処理で、3つの要件を満たすことができました。

<script>
$(function(){
    var currentDate = new Date();
    $('.mod-new').each(function(){
        var pass = <$mt:GetVar name="pass"$>;
        var content = '<img class="newmark" src="icon-new.png" height="13" width="37" alt="<$mt:GetVar name="pass"$>日以内の新着ブログ記事" title="<$mt:GetVar name="pass"$>日以内の新着ブログ記事">';
        var newmarkAttr = $(this).attr('title');
        newmarkAttr = newmarkAttr.replace(/年|月|日|時|分/g,':');
        newmarkAttr = newmarkAttr.replace(/\s|秒.*/g,'');
        var time = newmarkAttr.split(":");
        var entryDate = new Date(time[0], time[1]-1, time[2], time[3], time[4], time[5]);
        var now = (currentDate.getTime() - entryDate.getTime())/(60*60*1000);
        now = Math.ceil(now);
        if(now <= pass){
            $(this).append(content);
        }
    });
});
</script>

プラグインとか使えたほうが本当は助かるんですけど、導入することができないや代替案などの豆知識は常にメモしておくべきですね。

参考サイト

5
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
4