記事一覧に「New」アイコンをつけるメモです。
WEBサイト「MacBook Air とWordPressでこうなった」を参考にさせていただきました。。。。というか、そのまま使わせていただきました。
使い方
下記のコードを、functions.php に追加します。
function add_new_icon( $val ) { $days=7; $today=date('U'); $entry=get_the_time('U'); $diff=date('U',($today - $entry))/86400; if( $days > $diff ) { $icon_tag = '<img src="'.get_bloginfo('template_directory').'/img/new_icon.png" alt="New" class="new_icon" width="35" height="14" />'; } return $val.$icon_tag; } add_filter('the_date','add_new_icon'); add_filter('the_time','add_new_icon');
●Newアイコンの格納場所:テンプレートディレクトリーの中のimgディレクトリー
●Newアイコンの名前:new_icon.png(任意)
●Newアイコンにclass指定して調整:class=”new_icon”(任意)
タイトルの後に表示したい時は、add_filterの部分を下記コードに変更します。
add_filter(‘the_title’, ‘add_new_icon’);
※私のサイトでは、何故かタイトルの前に表示してしまうので、使用しませんでした。
Newアイコンを付ける日数は下記の数値を変更
$days=7; //7日間表示する
注意点
- このサイトでは、トップページの記事一覧にサムネイルを表示しているのですが、CSSで「li」タグ(下記コード内参照)に画像の大きさを指定していたので、Newアイコンの大きさがサムネイルと同じ大きさになってしまいました。
対処として、サムネイルを表示するコードを<div class=”thum”>で囲って画像の大きさを指定しました。また、Newアイコン自体にCLASS指定して位置を調整しました。
記事一覧にサムネイルを表示するコード
<ul> <?php $posts = get_posts('numberposts=10&cat=-1'); global $post; ?> <?php foreach($posts as $post): ?> <li> <div class="thum"><?php the_post_thumbnail('rel_tmn', array('alt'=>get_the_title(), 'title'=>get_the_title())); ?></div> <p class="newblog-title"><a href="<?php the_permalink(); ?>" alt="<?php the_title(); ?>"><?php the_title(); ?></a></p><span class="exe"><?php the_excerpt(); ?></span><span class="date"><?php the_time('m月d日'); ?></span> </li> <?php endforeach; ?> </ul>
サムネイルとNewアイコンのCSS
ul li div.thum { float:left; width:80px; height:80px; vertical-align:top; padding:0px 10px 0px 0px; } ul li img.new_icon { vertical-align:middle; }
#content .entry-content img.new_icon { display:none; }