WordPressのテンプレートを制作する際に個人的によく使っているコードスニペット集です。
プラグインは極力使いたくない派なんですが、そのわりに毎回ググってる気がするので、健忘録的にまとめておきます。
1年以上前の記事です。情報が古くなっている可能性があります。PHPやWPのバージョンによっては動かないものもあります。
jQueryなどの読み込み
WordPress内のjQueryではなく外部のjQueryを読み込ませる時に使います。jQueryの下の「function.js」は、自分が構築の際に色んなjsコードをまとめて書く時に使っているファイルで、jQueryとセットで読み込んでいます。不要なら削除するなり、名前を変更するなりして使ってください。
functions.php
// jQueryの置き換え
function load_cdn() {
if ( !is_admin() ) {
wp_deregister_script('jquery');
wp_enqueue_script('jquery', 'http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js', array(), '1.11.2');
wp_enqueue_script('function',get_bloginfo('template_url') . '/js/function.js', array('jquery'), '1.0');
}
}
add_action('init', 'load_cdn');
続きを読むのリンクに付いてくる #more-$id を削除する
記事の「続きを読む」のリンクに付いてくる #more-$id を削除します。
functions.php
// #more-$id を削除する。
function custom_content_more_link( $output ) {
$output = preg_replace('/#more-[\d]+/i', '', $output );
return $output;
}
add_filter( 'the_content_more_link', 'custom_content_more_link' );
アイキャッチを利用可能にする&オリジナルの画像サイズを追加する
アイキャッチを利用可能にします。また、オリジナルの画像サイズを追加します。オリジナルの画像サイズはテンプレート内で使用できます。
functions.php
// アイキャッチ画像
add_theme_support( 'post-thumbnails' );
add_image_size( 'origin_image', 600, 400, true );
page.php など
<?php the_post_thumbnail('origin_image');?>
記事の投稿画面でも使えるオリジナルの画像サイズを追加したい場合
add_image_size() ではなく、以下の方法で可能です。
functions.php
function add_custom_image_sizes() {
global $my_custom_image_sizes;
$my_custom_image_sizes = array(
'origin_image' => array(
'name' => '記事用の画像', // 選択肢のラベル名
'width' => 600, // 最大画像幅
'height' => 400, // 最大画像高さ
'crop' => false, // 切り抜きを行うかどうか
'selectable' => true // 選択肢に含めるかどうか
),
);
foreach ( $my_custom_image_sizes as $slug => $size ) {
add_image_size( $slug, $size['width'], $size['height'], $size['crop'] );
}
}
add_action( 'after_setup_theme', 'add_custom_image_sizes' );
function add_custom_image_size_select( $size_names ) {
global $my_custom_image_sizes;
$custom_sizes = get_intermediate_image_sizes();
foreach ( $custom_sizes as $custom_size ) {
if ( isset( $my_custom_image_sizes[$custom_size]['selectable'] ) && $my_custom_image_sizes[$custom_size]['selectable'] ) {
$size_names[$custom_size] = $my_custom_image_sizes[$custom_size]['name'];
}
}
return $size_names;
}
add_filter( 'image_size_names_choose', 'add_custom_image_size_select' );
投稿画面にオリジナルの編集ボタンを追加する
よく使うタグやクラス名などを投稿画面に追加できます。
functions.php
// HTMLエディタ編集
function add_my_quicktag() {
?>
<script type="text/javascript">
//QTags.addButton('ID', 'ボタンのラベル', '開始タグ', '終了タグ');
QTags.addButton('ed_h4', 'h4', '<h4>', '</h4>');
QTags.addButton('ed_h5', 'h5', '<h5>', '</h5>');
</script>
<?php
}
add_action('admin_print_footer_scripts', 'add_my_quicktag');
固定ページのパーマリンク設定
投稿のパーマリンク設定はダッシュボードの[設定]から可能ですが、固定ページの場合は以下の7行目の'%pagename%.html'
の部分を変更することで可能です。固定ページに拡張子を追加したい時などに便利です。
functions.php
// 固定ページのパーマリンク設定
add_action( 'init', 'mytheme_init' );
if ( ! function_exists( 'mytheme_init' ) ) {
function mytheme_init() {
global $wp_rewrite;
$wp_rewrite->use_trailing_slashes = false;
$wp_rewrite->page_structure = $wp_rewrite->root . '%pagename%.html';
// flush_rewrite_rules( false );
}
}
パンくずリストを作る
投稿ページ、固定ページそれぞれでパンくずリストを表示します。
投稿ページ:page.php
<ul id="topicpath">
<li><a href="<?php echo get_option('home'); ?>">HOME</a></li>
<li><a href="<?php $cat = get_the_category(); $cat = $cat[0]; echo get_category_link( $cat->term_id ); ?>"><?php echo $cat->cat_name; ?></a></li>
<li><?php the_title(''); ?></li>
</ul>
固定ページ:page.php
<ul id="topicpath">
<li><a href="<?php echo get_option('home'); ?>">HOME</a></li>
<?php foreach ( array_reverse(get_post_ancestors($post->ID)) as $parid ) { ?>
<li><a href="<?php echo get_page_link( $parid );?>" title="<?php echo get_page($parid)->post_name; ?>">
<?php echo get_page($parid)->post_name; ?></a></li>
<?php } ?>
<li><?php the_title(''); ?></li>
</ul>
親ページのスラッグを取得&判定
テンプレートを作る際、親ページと子ページで同じテンプレートを使い回したりしたい場合等に重宝します。
functions.php
// 親ページスラッグの取得
function is_parent_slug() {
global $post;
if ($post->post_parent) {
$post_data = get_post($post->post_parent);
return $post_data->post_name;
}
}
page.php など
<?php if(is_parent_slug()){
// 子ページの場合の処理
}else{
// 親ページの場合の処理
} ?>
カスタム投稿タイプの追加とパーマリンク設定
カスタム投稿タイプを使う場合は、合わせてパーマリンクの設定も気を使います。
functions.php
// カスタム投稿追加
function custom_post_types() {
$label = '投稿タイプ名の表記';
$slug = '投稿タイプ名';
$option = array(
'label' => $label,
'labels' => array(
'name' => $label,
'singular_name' => $label,
'add_new_item' => $label . 'を追加',
'add_new' => '新規追加',
'new_item' => '新規' . $label,
'view_item' => $label . 'を表示',
'not_found' => $label . 'は見つかりませんでした',
'not_found_in_trash' => 'ゴミ箱に' . $label . 'はありません。',
'search_items' => $label . 'を検索',
),
'capability_type' => 'post',
'menu_position' => 5,
'rewrite' => true,
'public' => true,
'query_var' => true,
'has_archive' => true,
'hierarchical' => false,
'supports' => array('title', 'editor'),
);
register_post_type('投稿タイプ名', $option);
}
add_action('init', 'custom_post_types');
// カスタム投稿 パーマリンク設定
add_action('init', 'myposttype_rewrite');
function myposttype_rewrite() {
global $wp_rewrite;
$queryarg = 'post_type=投稿タイプ名&p=';
$wp_rewrite->add_rewrite_tag('%投稿タイプ名_id%', '([^/]+)',$queryarg);
$wp_rewrite->add_permastruct('投稿タイプ名', '/投稿タイプ名/%投稿タイプ名_id%.html', false);
}
add_filter('post_type_link', 'myposttype_permalink', 1, 3);
function myposttype_permalink($post_link, $id = 0, $leavename) {
global $wp_rewrite;
$post = &get_post($id);
if ( is_wp_error( $post ) )
return $post;
$newlink = $wp_rewrite->get_extra_permastruct($post->post_type);
$newlink = str_replace('%'.$post->post_type.'_id%', $post->ID, $newlink);
$newlink = home_url(user_trailingslashit($newlink));
return $newlink;
}
検索フォームをカスタマイズする
デフォルトの<?php get_search_form(); ?>
で出力される検索フォームの内容を変更します。
functions.php
// 検索フィールド
function my_search_form( $form ) {
$form = '<form role="search" method="get" id="searchform" action="'.home_url( '/' ).'">
<input type="text" value="' . get_search_query() . '" name="s" id="s" /><input type="submit" id="searchsubmit" value="サイト内検索" />
</form>';
return $form;
}
add_filter( 'get_search_form', 'my_search_form' );
ページネーションを設置する
参考サイトのものだと各ページに長い記述をすることになるので、functions.phpにまとめて書けるようにしています。
functions.php
// ページャー
function pagerNavi($maxNum,$pCur){
global $wp_rewrite;
$paginate_base = get_pagenum_link(1);
if(strpos($paginate_base, '?') || ! $wp_rewrite->using_permalinks()){
$paginate_format = '';
$paginate_base = add_query_arg('paged','%#%');
}
else{
$paginate_format = (substr($paginate_base,-1,1) == '/' ? '' : '/') .
user_trailingslashit('page/%#%/','paged');;
$paginate_base .= '%_%';
}
echo paginate_links(array(
'base' => $paginate_base,
'format' => $paginate_format,
'total' => $maxNum,
'mid_size' => 4,
'current' => ($pCur ? $pCur : 1),
'prev_text' => '«',
'next_text' => '»',
));
}
archive.php など
<?php pagerNavi($wp_query->max_num_pages,$paged); ?>
以上こんな感じで、これくれらいならプラグイン無しでやっていけるようです。
*参考サイト
・WordPressで追加した画像サイズを本文に挿入できるようにする | Simple Colors
・[WordPress]親ページのスラッグを取得する | ホームページ制作 Webデザイン事務所 ハイファイブクリエイト
・パンくずリストの追加方法 -WordPressの投稿・固定ページ対応-|ThePresentNote
・WordPressカスタム投稿タイプのパーマリンク設定とカスタマイズ | memocarilog
・カスタムポストのパーマリンクを投稿IDにする / よくあるWordPress | ゆるぶ
・WordPressの検索機能をもっと使いやすくする | Webクリエイターボックス
・プラグイン不要!WordPressのページャー(ページネーション)機能を簡単に実装する方法 – Kowappa