テンプレートファイルのカスタマイズで使えそうなソースのサンプルをつらつらと書き散らしてみる。その2はこちら。
タイトルの文字数制限
一定数以上のタイトルを省略(抜粋)する。
下記サンプルだと10文字まで拾って以下を三点リーダにしています
<?php $title= mb_substr($post->post_title,0,10); echo '<h1>'.$title.'…</h1>'; ?>
検索キーワードとヒット数の表示
search.phpとかに入れると結構見栄えがいい。
<?php $allsearch =& new WP_Query("s=$s&showposts=-1"); $key = wp_specialchars($s, 1); $count = $allsearch->post_count; if($count!=0){ echo '<em>'.$key.'</em>で検索した結果、<span class="count">'.$count.'</span>件ヒットしました'; }else{ echo '<em>'.$key.'</em>で検索しましたが、何も見つかりませんでした'; } ?></p>
特定のカテゴリーに投稿された記事だけ表示
重要なのはループの前のquery_postsとループの後のwp_reset_query()。
query_postsを使う場合wp_reset_query()を最後につけないとqueryの指定が後のループに引き継がれる。
カテゴリID5の本文だけ表示するサンプル
<?php query_posts('cat=5');if (have_posts()) :?> <?php while (have_posts()) : the_post(); ?> <div class="post"> <?php the_content(__('Read More »','my84')); ?> </div> <?php endwhile;?> <?php wp_reset_query();endif;?>
IDで指定した記事の本文だけを表示
あるページ(または記事)の本文だけサイトのトップとかに表示したい時に使える。
functions.php
function site_content($my_id){ $post_home = get_post($my_id); $content = $post_home->post_content; $content = wpautop($content); return $content; }
ショートコードに対応させる場合
$content=wpautop($content);
の前に、
$content = do_shortcode($content);
を追加する。
テンプレートファイル側
引数は表示する記事のID
<?php echo site_content(2);?>
wpautopはpタグとかを自動でつけて整形するwordpress内の関数。(formatting.php内)
カテゴリーで条件分岐
「もしカテゴリーID5の子カテゴリなら」とか「カテゴリースラッグがhogeなら」みたいな条件指定
$category = get_the_category(); if($category[0]->category_parent==5){ //ID5ならtrue }elseif($category[0]->category_nicename=='hoge'){ //スラッグがhogeならtrue }else{ //他 }