
クライアントワークやブログでのWordPressのカスタマイズ時に使用頻度の高いコードをまとめてみました。
基本的には、ネット上のコードを自分好みにカスタマイズしているので大元のコードの記載記事というのがあり、覚えている限りは記載しております。
Templates e PHP para WordPress / fore
条件分岐のカスタマイズコード
とにかく使用頻度の高い条件分岐。
TOPページにはアレを表示してあの記事には表示しない!みたいな。
TOPページや投稿、記事などに別の内容を表示する
<?php if (is_home()) { ?>
TOPにのみ表示する内容
<?php } else if (is_page('13')) { ?>
記事ID「13」の固定ページのみ表示する内容
<?php } else if (in_category('3')) { ?>
カテゴリーID「3」の投稿ページのみ表示する内容
<?php } else { ?>
その他のページに表示する内容
<?php } ?>
スマートフォンかPCかで表示を分ける
<?php if ( function_exists('wp_is_mobile') && wp_is_mobile() ) :?>
スマートフォン用コンテンツをココに書きます。
<?php else: ?>
パソコン用コンテンツをココに書きます。
<?php endif; ?>
※wordpress3.4以上
wp_is_mobile関数 – WordPress3.4から実装されたパソコン用サイトとスマートフォン用サイトを分ける条件分岐タグ
カスタムフィールドの値の有無で表示を変更
<?php if(post_custom('値の名前')): ?>
値のある場合の処理
<?php else : ?>
ない場合の処理
<?php endif; ?>
ログインしているかどうかで表示を分ける
<?php if (is_user_logged_in()) :?>
ログインしている時の表示
<?php else :?>
<p class="setumei">
ログインしていない場合の表示
<?php endif; ?>
カテゴリに応じてsingle.phpを変える
<?php
$post = $wp_query->post;
if ( in_category('5') ) {
include(TEMPLATEPATH . '/single1.php');
} else {
include(TEMPLATEPATH . '/single2.php');
}
?>
カテゴリIDが5の場合はsingle1.phpを。それ以外はsingle2.php
ページのリスト
クライアントワークのサイドバー等によく表示するメニューリスト
特定のIDを含むページのリスト
<ul >
<?php wp_list_pages('sort_colomn=menu_order &include=1,2,3,4,5,6,7& title_li'); ?>
</ul>
特定のIDを除くページのリスト
<ul >
<?php wp_list_pages('sort_colomn=menu_order &exclude=1,2,3,4,5,6,7,8& title_li'); ?>
</ul>
子ページを表示しない
<ul>
<?php wp_list_pages('sort_colomn=menu_order & title_li=&depth=1'); ?>
</ul>
WordPressの文字数制限
タイトルの文字数制限
<?php
$title= mb_substr($post->post_title,0,19); echo $title;
?>
内容(コンテンツ)の文字数制限
<?php echo mb_substr(strip_tags($post-> post_content),0,100).'...'; ?>
100を好きな数に
カスタムフィールドの値の文字数制限
<?php
$pattern = '/(^.{10})(.+)/u';
$subject = post_custom('値の名称');
$matches = array();
preg_match($pattern, $subject , $matches);
if ($matches[2] != '') {
$out = $matches[1] . '...';
} else {
$out = $subject;
}
echo($out);
?>
10文字に制限
WordPressのいろいろなコンテンツ表示
カテゴリーも表示する新着一覧

<div id="news">
<h2 class="entry-title">What's New</h2>
<ul>
<?php
// ▽ポストタイプとタクソノミーを入力
$post_type = 'post';
$taxonomy = 'category';
// △
$args=array(
'post_type' => $post_type,
'post_status' => 'publish',
'posts_per_page' => 3,
'orderby' => 'date',
'order' => DESC,
'caller_get_posts'=> 1
);
$my_posts = get_posts($args);
foreach ($my_posts as $post) {
setup_postdata($post);
$post_title = $post->post_title;
?>
<li>
<span class='date'><?php the_time('Y年m月d日'); ?></span>
<?php
$terms = get_the_terms( $post->ID, $taxonomy );
if ( $terms && ! is_wp_error( $terms ) ) :
$draught_links = array();
foreach ( $terms as $term ) {
echo '<a class="' . $term->slug . '" href="' . home_url( '/' ) . $term->taxonomy .'/'. $term->slug . '">' . $term->name . '</a>';
}
endif;
$days=7; $today=date('U'); $entry=get_the_time('U'); $diff1=date('U',($today - $entry))/86400;
if ($days > $diff1) { echo '<img src="' . get_bloginfo('template_url') . '/images/new.gif" alt="New" />'; }
?>
</span><br />
<a href="<?php the_permalink();?>"><?php the_title(); ?></span></a>
</li>
<?php } ?>
</ul>
</div>
どや!?WordPressでのサイト制作を簡単にしてくれる魔法のコード
現在表示されている記事を除いた
サムネイルつき新着一覧
<!--新着記事-->
<h4 class="kanren">新着記事</h4>
<div class="sumbox02">
<div id="topnews">
<div><?php
foreach((get_the_category()) as $cat) {
$cat_id = 0 ;
break ;
}
$query = 'cat=' . $cat_id. '&showposts=5'; //表示本数です
query_posts($query) ;
?>
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<dl><dt>
<?php if ($post->ID == $cur_post->ID) : ?>
<?php else :?>
<a href="<?php the_permalink() ?>" title="<?php the_title_attribute(); ?>">
<?php if ( has_post_thumbnail() ): // サムネイルを持っているときの処理 ?>
<?php echo get_the_post_thumbnail($post->ID, 'thumb110'); ?>
<?php else: // サムネイルを持っていないときの処理 ?>
<img src="<?php bloginfo('template_directory'); ?>/images/no-img.png" alt="no image" title="no image" width="110" height="110" />
<?php endif; ?>
</a>
<?php endif; ?>
</dt>
<dd>
<?php if ($post->ID == $cur_post->ID) : ?>
<?php else :?>
<h4 class="saisin">
<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h4>
<p class="basui">
<?php echo mb_substr(strip_tags($post-> post_content),0,35).'...'; ?></p>
<p class="motto"><a href="<?php the_permalink(); ?>">記事を読む</a></p>
<?php endif; ?>
</dd></dl>
<?php endwhile; else: ?>
<p>記事がありません</p>
<?php endif; ?>
<?php wp_reset_query(); ?>
</div>
</div>
</div>
※サムネイル表示の為にfunctions.phpに以下を追加
//アイキャッチサムネイル
add_image_size('thumb110',110,110,true);
サイズやCSSは好きに適宜修正して下さい。
表示している記事と同じカテゴリーの記事を
サムネイル付きで表示
<!--関連記事-->
<h4 class="kanren">関連記事</h4>
<div class="sumbox02">
<?php
$cur_post = $wp_query->get_queried_object();
$post_cats = get_the_category($cur_post->ID);
?>
<div id="topnews">
<div><?php
foreach((get_the_category()) as $cat) {
$cat_id = $cat->cat_ID ;
break ;
}
$query = 'cat=' . $cat_id. '&showposts=5'; //5が表示本数です
query_posts($query) ;
?>
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<dl><dt>
<?php if ($post->ID == $cur_post->ID) : ?>
<?php else :?>
<a href="<?php the_permalink() ?>" title="<?php the_title_attribute(); ?>">
<?php if ( has_post_thumbnail() ): // サムネイルを持っているときの処理 ?>
<?php echo get_the_post_thumbnail($post->ID, 'thumb110'); ?>
<?php else: // サムネイルを持っていないときの処理 ?>
<img src="<?php bloginfo('template_directory'); ?>/images/no-img.png" alt="no image" title="no image" width="110" height="110" />
<?php endif; ?>
</a>
<?php endif; ?>
</dt>
<dd>
<?php if ($post->ID == $cur_post->ID) : ?>
<?php else :?>
<h4 class="saisin">
<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h4>
<p class="basui">
<?php echo mb_substr(strip_tags($post-> post_content),0,35).'...'; ?></p>
<p class="motto"><a href="<?php the_permalink(); ?>">記事を読む</a></p>
<?php endif; ?>
</dd></dl>
<?php endwhile; else: ?>
<p>記事がありません</p>
<?php endif; ?>
<?php wp_reset_query(); ?>
</div>
</div>
</div>
<!--/関連記事-->
※サムネイル表示の為にfunctions.phpに以下を追加
※サムネイルが無いとき用の「no-img.png」は、予めimagesフォルダにUPしておいて下さい。
//アイキャッチサムネイル
add_image_size('thumb110',110,110,true);
サイズやCSSは好きに適宜修正して下さい。
古い記事から表示
<?php query_posts('posts_per_page=10&order=ASC&' . $query_string); ?>
//ここから下は記事ループタグ
<?php if(have_posts()): while(have_posts()): the_post(); ?>
<?php the_title(); ?>
<?php the_content(); ?>
<?php endwhile; endif; ?>
特定のIDの記事内容を取得
<?php $loop = new WP_Query('page_id=4'); ?>
<?php while ( $loop->have_posts() ) : $loop->the_post();
/* ループ開始 */ ?>
<?php the_content(); ?>
<?php endwhile; ?>
※4を好きなIDに変更
新着情報を表示(任意のカテゴリーの記事を表示)
<?php the_date(); ?>
<div id="topnews">
<a href="<?php bloginfo('rss2_url'); ?>"><img src="<?php bloginfo('template_directory'); ?>/images/rss.jpg" /></a>
<div><?php $posts = get_posts('numberposts=6&category=0&order=desc'); ?>
<?php foreach($posts as $post): ?>
<dl><dt><span><?php the_time('Y.m.d'); ?></span></dt>
<dd><a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a></dd></dl>
<?php endforeach; ?>
</div></div>
新着を6件表示します。「6」は好きに変更できます。カテゴリIDも指定可能。
複数のカスタム投稿を表示
<?php
$args = array(
'post_type' => array('カスタム投稿タイプ名1', 'カスタム投稿タイプ名2'),
'posts_per_page' => 5,
); ?>
<?php $my_query = new WP_Query( $args ); ?>
<?php while ( $my_query->have_posts() ) : $my_query->the_post(); ?>
<h1 class="entry-title"><?php the_title(); ?></h1>
<?php the_excerpt(); ?>
<a class="more-link" href="<?php the_permalink() ?>">詳しく見る</a>
<?php endwhile; // end of the loop. ?>
<?php wp_reset_postdata(); ?>
「続きを読む」を画像に
<?php the_content('<div><br /><img src="<?php bloginfo('template_directory'); ?>/images/next.jpg" alt="続きを読む" /></div>'); ?>
※画像(next.jpgをUP)
SNS(ソーシャルボタン)の表示
各種SNSボタンの表示
<ul>
<li>
<a href="https://twitter.com/share" class="twitter-share-button" data-count="vertical" data-via="khoshino" data-url="<?php the_permalink(); ?>" data-text="<?php the_title(); ?>">Tweet</a><script type="text/javascript" src="//platform.twitter.com/widgets.js"></script>
</li>
<li>
<iframe src="http://www.facebook.com/plugins/like.php?href=<?php the_permalink(); ?>&layout=box_count&show_faces=false&width=50&action=like&colorscheme=light&height=62" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:70px; height:62px;" allowTransparency="true"></iframe>
</li>
<li><script type="text/javascript" src="https://apis.google.com/js/plusone.js"></script><g:plusone size="tall" href="<?php the_permalink(); ?>"></g:plusone></li>
<li>
<a href="http://b.hatena.ne.jp/entry/<?php the_permalink(); ?>" class="hatena-bookmark-button" data-hatena-bookmark-title="<?php the_title(); ?>|<?php bloginfo('name'); ?>" data-hatena-bookmark-layout="vertical" title="このエントリーをはてなブックマークに追加"><img src="http://b.st-hatena.com/images/entry-button/button-only.gif" alt="このエントリーをはてなブックマークに追加" width="20" height="20" style="border: none;" /></a><script type="text/javascript" src="http://b.st-hatena.com/js/bookmark_button.js" charset="utf-8" async="async"></script>
</li>
</ul>
Twitterのツイートボタン、Facebookのいいね!ボタン、Google+のボタン、はてなブックマークのボタンなどを、プラグインを使わずに、四角のボックス形式で設置する方法。
Pocketの表示
<a href="https://getpocket.com/save"
class="pocket-btn"
data-lang="en"
data-save-url="<?php get_permalink(); ?>"
data-pocket-count="vertical"
data-pocket-align="left" >Pocket</a>
<script type="text/javascript">!function(d,i){if(!d.getElementById(i)){var j=d.createElement("script");j.id=i;j.src="https://widgets.getpocket.com/v1/j/btn.js?v=1";var w=d.getElementById(i);d.body.appendChild(j);}}(document,"pocket-btn-js");</script>
「pocket」のWordPressブログへのボタン設置方法。そしてわかった衝撃の事実。これは無視できない。
知っていると便利かもしれないコード
外部RSSを取得して表示
<?php include_once(ABSPATH . WPINC . '/feed.php');
$rss = fetch_feed(array(
'http://feeds.feedburner.com/WebmasterCentral',
//RSSフィード1
'http://ja.wordpress.org/feed/'
//RSSフィード2
));
if (!is_wp_error( $rss ) ) :
$rss->set_cache_duration(1800);
$rss->init();
$maxitems = $rss->get_item_quantity(10);
$rss_items = $rss->get_items(0, $maxitems);
date_default_timezone_set('Asia/Tokyo');
endif;
?>
<dl>
<?php if ($maxitems == 0) echo '<dt>No items.</dt>';
else
foreach ( $rss_items as $item ) : ?>
<dt>
<a href='<?php echo $item->get_permalink(); ?>' target="_blank"><?php echo $item->get_title(); ?></a><br />
by <?php echo $item->get_feed()->get_title(); ?><br />
<?php echo mb_substr(strip_tags($item->get_description()), 0, 100); ?>・・・<a href='<?php echo $item->get_permalink(); ?>' target="_blank">続きを読む</a>
</dt>
<dd>(<?php echo $item->get_date("Y-n-j H:i:s"); ?>)</dd>
<?php endforeach; ?>
</dl>
複数外部RSSフィードをWordPressで表示
カスタム投稿タイプでも「add quicktag」を使用する
functions.phpに以下を記載
//カスタム投稿タイプでaddquicktagを使う
add_filter( 'addquicktag_post_types', 'my_addquicktag_post_types' );
/**
* Return array $post_types with custom post types
*
* @param $post_type Array
* @return $post_type Array
*/
function my_addquicktag_post_types( $post_types ) {
$post_types[] = 'カスタムポストの名前';
$post_types[] = 'カスタムポストの名前';
$post_types[] = 'カスタムポストの名前';
return $post_types;
}
カスタム投稿タイプにAddQuicktagを適用させる
カスタム投稿タイプもRSS配信
functions.phpに
/* カスタム投稿タイプを RSS で配信 */
function custom_post_rss_set($query) {
if(is_feed()) {
$query->set('post_type',
Array(
'post',
'カスタムポスト名',
'カスタムポスト名',
'カスタムポスト名'
)
);
return $query;
}
}
add_filter('pre_get_posts', 'custom_post_rss_set');
WordPress でカスタム投稿タイプの RSS を配信する方法
管理者以外には管理画面見せない
// 管理者以外には管理画面見せない
function forbid_admin_page() {
// グローバル宣言
global $current_user;
// 現在のユーザー情報を取得
get_currentuserinfo();
// ユーザーレベルが 10(管理者)未満であれば
if ( $current_user->user_level < 10 ){
// トップページヘ
header( 'Location: ' . get_bloginfo('url') . '/' );
}
}
add_action('admin_init','forbid_admin_page');
[WordCamp資料]WordPressでWebアプリケーションを作る方法~Croppy編~
Googleに表示されるパンくずリスト
<?php /*--- パンくずリスト --- */ ?>
<div id="breadcrumb">
<div itemscope itemtype="http://data-vocabulary.org/Breadcrumb">
<a href="<?php echo home_url(); ?>" itemprop="url">
<span itemprop="title">ホーム</span>
</a> ›
</div>
<?php /*--- カテゴリーが階層化している場合に対応させる --- */ ?>
<?php $postcat = get_the_category(); ?>
<?php $catid = $postcat[0]->cat_ID; ?>
<?php $allcats = array($catid); ?>
<?php
while(!$catid==0) { /* すべてのカテゴリーIDを取得し配列にセットするループ */
$mycat = get_category($catid); /* カテゴリーIDをセット */
$catid = $mycat->parent; /* 上で取得したカテゴリーIDの親カテゴリーをセット */
array_push($allcats, $catid);
}
array_pop($allcats);
$allcats = array_reverse($allcats);
?>
<?php /*--- 親カテゴリーがある場合は表示させる --- */ ?>
<?php foreach($allcats as $catid): ?>
<div itemscope itemtype="http://data-vocabulary.org/Breadcrumb">
<a href="<?php echo get_category_link($catid); ?>" itemprop="url">
<span itemprop="title"><?php echo get_cat_name($catid); ?></span>
</a> ›
</div>
<?php endforeach; ?>
<div><?php the_title(); ?></div>
</div> <!--- end [breadcrumb] -->
[Я]パンくずリストをGoogle検索結果にも表示・反映させる方法
[Å] パンクズをGoogleの検索結果に表示させる方法を紹介!あっさりと設置できました!!
WordPressをカスタマイズしたければ
とにかく読んどけ!って記事
WordPressのfunctions.phpに書いておくといいかもしれないコードいろいろ
ていうかwebdesignrecipies全部
もう覚えなくても大丈夫!?WordPressの条件分岐タグの使い方まとめ
WordPressのカスタマイズの要
「カスタム投稿タイプ」はここで学べ!
WordPressのテンプレートタグを使ってコメントフォームをカスタマイズする方法
「Oxy notes」さんのカスタム投稿についての記事は秀逸です。
上記記事から順を追って学びましょう!!
まとめ
WordPressのカスタマイズは「条件分岐」と「カスタム投稿」がわかるとかなり出来る事が広がります。PHPが苦手でもいろいろできるのがWordpressの楽しいところでもあるかもしれませんね。