2017.10.27WEB - WordPress

WordPressのテーマを自作する ? その2(functions.php編)

自分がfunctions.phpに基本的に入れてるやつ

前回からめちゃめちゃ時間経ってない?
ということで結構人それぞれな気がするこのファイル。私の場合。

/** サムネイル有効 **/
/*------------------------------------------*/
add_theme_support('post-thumbnails');

/** 投稿の設定 **/
/*------------------------------------------*/
$mypost_label = '取扱製品'; // ラベル
$mypost_slug  = 'products'; // スラッグ

/** 投稿の変更 **/
/*------------------------------------------*/
function edit_admin_menus() {  
  global $menu, $submenu, $mypost_label;
  $menu[5][0] = $mypost_label;
  $submenu['edit.php'][5][0] = $mypost_label.'一覧';
}
function revcon_change_post_object() {
  global $wp_post_types, $mypost_label;
  $labels = &$wp_post_types['post']->labels;
  $labels->name = $mypost_label;
  $labels->singular_name = $mypost_label;
  $labels->add_new = '新規追加';
  $labels->add_new_item = $mypost_label .'を追加';
  $labels->edit_item = $mypost_label .'の編集';
  $labels->new_item = $mypost_label;
  $labels->view_item = $mypost_label .'の表示';
  $labels->search_items = $mypost_label .'を検索';
  $labels->not_found = $mypost_label .'が見つかりませんでした。';
  $labels->not_found_in_trash = 'ゴミ箱内に' .$mypost_label .'が見つかりませんでした。';
  $labels->all_items = '全ての' .$mypost_label;
  $labels->menu_name = $mypost_label;
  $labels->name_admin_bar = $mypost_label;
} 
add_action('admin_menu', 'edit_admin_menus');
add_action('init', 'revcon_change_post_object');

/** 投稿もarchive.phpで表示させる **/
/*------------------------------------------*/
function post_has_archive($args, $post_type) {
  global $mypost_slug;
  if ('post' == $post_type) {
    $args['rewrite'] = true;
    $args['has_archive'] = $mypost_slug; // 上記で設定したスラッグ。上記設定してない場合は文字列(例:'products')
  }
  return $args;
}
add_filter('register_post_type_args', 'post_has_archive', 10, 2);

/** 要らないメニュー非表示 **/
/*------------------------------------------*/
function remove_admin_menus() {
  global $menu;
  unset($menu[25]); // コメント
}
add_action('admin_menu', 'remove_admin_menus');

/** 設定ページにキーワード追加 **/
/*------------------------------------------*/
function add_site_word_field($whitelist_options) {
  $whitelist_options['general'][] = 'site_word';
  return $whitelist_options;
}
add_filter('whitelist_options', 'add_site_word_field');
function regist_site_word_field() {
  add_settings_field('site_word', 'サイトキーワード', 'display_site_word', 'general');
}
add_action('admin_init', 'regist_site_word_field');
function display_site_word() {
  $site_word = get_option('site_word');
?>
  <input name="site_word" value="<?php echo esc_html( $site_word ); ?>" class="regular-text" style="border:1px solid #ddd;box-shadow:inset 0 1px 2px rgba(0,0,0,.07);">
  <p>このサイトのキーワードを半角カンマ(,)区切りで設定出来ます。</p>
<?php
}

/** SVG対応 **/
/*------------------------------------------*/
function cc_mime_types ( $mimes )  { 
  $mimes [ 'svg' ]  =  'image/svg+xml' ; 
  return $mimes ; 
} 
add_filter ( 'upload_mimes' ,  'cc_mime_types' ) ;
function fix_svg_thumb_display() {
  echo '<style>
    td.media-icon img[src$=".svg"], img[src$=".svg"].attachment-post-thumbnail { 
      width: 100% !important; 
      height: auto !important; 
    }
</style>
  ';
}
add_action('admin_head', 'fix_svg_thumb_display');

/** editor-style.cssを有効にする **/
/*------------------------------------------*/
add_editor_style('editor-style.css');
function custom_editor_settings( $initArray ){
 $initArray['body_class'] = 'editor-area';
 return $initArray;
}
add_filter('tiny_mce_before_init', 'custom_editor_settings');

/*------------------------------------------
 * 表への出力関連
 *----------------------------------------*/

/** wp_head()の制御 **/
/*------------------------------------------*/
remove_action('wp_head', 'feed_links', 2);
remove_action('wp_head', 'feed_links_extra', 3);
remove_action('wp_head', 'rsd_link');
remove_action('wp_head', 'wlwmanifest_link');
remove_action('wp_head', 'index_rel_link');
remove_action('wp_head', 'start_post_rel_link', 10, 0);
remove_action('wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0);
remove_action('wp_head', 'wp_print_styles', 8);
remove_action('wp_head', 'wp_print_head_scripts', 9);
remove_action('wp_head', 'wp_generator');
remove_action('wp_head', 'rel_canonical');
remove_action('wp_head', 'rest_output_link_wp_head');
remove_action('wp_head', 'wp_oembed_add_discovery_links');
remove_action('wp_head', 'wp_oembed_add_host_js');

/** 絵文字のコードを消す **/
/*------------------------------------------*/
remove_action('admin_print_scripts', 'print_emoji_detection_script');
remove_action('admin_print_styles', 'print_emoji_styles');
remove_filter('the_content_feed', 'wp_staticize_emoji');
remove_filter('comment_text_rss', 'wp_staticize_emoji');
remove_filter('wp_mail', 'wp_staticize_emoji_for_email');
remove_action('wp_head', 'print_emoji_detection_script', 7);
remove_action('wp_print_styles', 'print_emoji_styles');

/** タイトルタグの区切り **/
/*------------------------------------------*/
/**- タイトルタグをサポートさせる -**/
function mytheme_setup() {
  add_theme_support('title-tag');
}
add_action('after_setup_theme', 'mytheme_setup');

/**- タイトルタグからディスクリプションを削除 -**/
function remove_tagline($title) {
  if (isset($title['tagline'])) {
    unset($title['tagline']);
  }
  return $title;
}
add_filter( 'document_title_parts', 'remove_tagline' );

/**- タイトルタグの仕切り「-」を「|」へ変更 -**/
function my_document_title_separator($sec) {
  $sec = "|";
  return $sec;
}
add_filter('document_title_separator', 'my_document_title_separator');

/** Pagination **/
/*------------------------------------------*/
function pagination($pages = '', $range = 2) {
  $showitems = ($range * 2)+1; //表示するページ数(5ページ)

  global $paged; //現在のページ値
  if(empty($paged)) $paged = 1; //デフォルトのページ

  if($pages == '') {
    global $wp_query;
    $pages = $wp_query->max_num_pages; //全ページ数を取得
    if(!$pages) { //全ページ数が空の場合は、1とする
      $pages = 1;
    }
  }

  if(1 != $pages) { //全ページが1でない場合は表示

    echo "<div class=\"pagination\">\n";
    echo "<ul>\n";

    //Prev:現在のページ値が1より大きい場合は表示
    if($paged > 1) echo "<li class=\"prev\"><a href='".get_pagenum_link($paged - 1)."'>Prev</a></li>\n";

    for ($i=1; $i <= $pages; $i++) {
      if (1 != $pages &&( !($i >= $paged+$range+1 || $i <= $paged-$range-1) || $pages <= $showitems )) {

        //現在のページ数と一致すればactiveクラス付与
        echo ($paged == $i)? "<li class=\"active\">".$i."</li>\n":"<li><a href='".get_pagenum_link($i)."'>".$i."</a></li>\n";
      }
    }

    //Next:総ページ数より現在のページ値が小さい場合
    if ($paged < $pages) echo "<li class=\"next\"><a href=\"".get_pagenum_link($paged + 1)."\">Next</a></li>\n";
    echo "</ul>\n";
    echo "</div>\n";
  }
}

/**- Paginationのテンプレートへの表示方法は以下 -**/
/*
<?php
if (function_exists("pagination")) {
	pagination($additional_loop->max_num_pages);
}
?>
*/

/** テンプレートに持ち込んで使いまわしたい変数 **/
/*------------------------------------------*/
$tmp_dir  = get_template_directory_uri(); // テンプレートディレクトリURL
$site_url = home_url(); // ホームページURL

説明

サムネイル機能を有効にする

/** サムネイル有効 **/
/*------------------------------------------*/
add_theme_support('post-thumbnails');

記事毎のアイキャッチ機能を有効にします。

投稿の設定

/** 投稿の設定 **/
/*------------------------------------------*/
$mypost_label = '取扱製品'; // ラベル
$mypost_slug  = 'products'; // スラッグ

デフォルトの「投稿」の名称及びスラッグをカスタマイズするために、変数に入れておきます。後ほど使用します。

投稿の変更

/** 投稿の変更 **/
/*------------------------------------------*/
function edit_admin_menus() {  
  global $menu, $submenu, $mypost_label;
  $menu[5][0] = $mypost_label;
  $submenu['edit.php'][5][0] = $mypost_label.'一覧';
}
function revcon_change_post_object() {
  global $wp_post_types, $mypost_label;
  $labels = &$wp_post_types['post']->labels;
  $labels->name = $mypost_label;
  $labels->singular_name = $mypost_label;
  $labels->add_new = '新規追加';
  $labels->add_new_item = $mypost_label .'を追加';
  $labels->edit_item = $mypost_label .'の編集';
  $labels->new_item = $mypost_label;
  $labels->view_item = $mypost_label .'の表示';
  $labels->search_items = $mypost_label .'を検索';
  $labels->not_found = $mypost_label .'が見つかりませんでした。';
  $labels->not_found_in_trash = 'ゴミ箱内に' .$mypost_label .'が見つかりませんでした。';
  $labels->all_items = '全ての' .$mypost_label;
  $labels->menu_name = $mypost_label;
  $labels->name_admin_bar = $mypost_label;
} 
add_action('admin_menu', 'edit_admin_menus');
add_action('init', 'revcon_change_post_object');

デフォルトの「投稿」を、上記にて設定した名称へ変更します。

投稿もarchive.phpで表示させる

/** 投稿もarchive.phpで表示させる **/
/*------------------------------------------*/
function post_has_archive($args, $post_type) {
  global $mypost_slug;
  if ('post' == $post_type) {
    $args['rewrite'] = true;
    $args['has_archive'] = $mypost_slug; // 上記で設定したスラッグ。上記設定してない場合は文字列(例:'products')
  }
  return $args;
}
add_filter('register_post_type_args', 'post_has_archive', 10, 2);

普通の投稿もカスタム投稿タイプもカテゴリアーカイブも、私は全部「archive.php」で表示させちゃうので上記を追記。「category.php」は使ってません。
「category.php」を使用される方は上記のコードは必要ないかと思います。

要らないメニュー非表示

/** 要らないメニュー非表示 **/
/*------------------------------------------*/
function remove_admin_menus() {
  global $menu;
  unset($menu[25]); // コメント
}
add_action('admin_menu', 'remove_admin_menus');

コメント機能は基本的に使ってないので消しちゃいます。
他にも、使用しないメニューは上記のメニュー番号を変更して適用することで、消すことができます。
※デフォルトである項目の場合。別の場合は書き方変わります。

設定ページにキーワード追加

/** 設定ページにキーワード追加 **/
/*------------------------------------------*/
function add_site_word_field($whitelist_options) {
  $whitelist_options['general'][] = 'site_word';
  return $whitelist_options;
}
add_filter('whitelist_options', 'add_site_word_field');
function regist_site_word_field() {
  add_settings_field('site_word', 'サイトキーワード', 'display_site_word', 'general');
}
add_action('admin_init', 'regist_site_word_field');
function display_site_word() {
  $site_word = get_option('site_word');
?>
  <input name="site_word" value="<?php echo esc_html( $site_word ); ?>" class="regular-text" style="border:1px solid #ddd;box-shadow:inset 0 1px 2px rgba(0,0,0,.07);">
  <p>このサイトのキーワードを半角カンマ(,)区切りで設定出来ます。</p>
<?php
}

「設定」→「一般」には、ディスクリプションを記入するフィールドはあるのですが、キーワードを設定する項目がありませんので追加します。
現在ではあまり意味を為さないと言われていますが、一応。

SVG対応

/** SVG対応 **/
/*------------------------------------------*/
function cc_mime_types ( $mimes )  { 
  $mimes [ 'svg' ]  =  'image/svg+xml' ; 
  return $mimes ; 
} 
add_filter ( 'upload_mimes' ,  'cc_mime_types' ) ;
function fix_svg_thumb_display() {
  echo '<style>
    td.media-icon img[src$=".svg"], img[src$=".svg"].attachment-post-thumbnail { 
      width: 100% !important; 
      height: auto !important; 
    }
</style>
  ';
}
add_action('admin_head', 'fix_svg_thumb_display');

デフォルトだとメディアへのSVGのアップロードは許可されていませんので、追加できるようにします。

editor-style.cssを有効にする

/** editor-style.cssを有効にする **/
/*------------------------------------------*/
add_editor_style('editor-style.css');
function custom_editor_settings( $initArray ){
 $initArray['body_class'] = 'editor-area';
 return $initArray;
}
add_filter('tiny_mce_before_init', 'custom_editor_settings');

WYSYWYGエディタに、独自のスタイルを適用します。
functions.phpと同ディレクトリにeditor-style.cssを追加しておきましょう。

wp_head()の制御 / 絵文字のコードを消す

/** wp_head()の制御 **/
/*------------------------------------------*/
remove_action('wp_head', 'feed_links', 2);
remove_action('wp_head', 'feed_links_extra', 3);
remove_action('wp_head', 'rsd_link');
remove_action('wp_head', 'wlwmanifest_link');
remove_action('wp_head', 'index_rel_link');
remove_action('wp_head', 'start_post_rel_link', 10, 0);
remove_action('wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0);
remove_action('wp_head', 'wp_print_styles', 8);
remove_action('wp_head', 'wp_print_head_scripts', 9);
remove_action('wp_head', 'wp_generator');
remove_action('wp_head', 'rel_canonical');
remove_action('wp_head', 'rest_output_link_wp_head');
remove_action('wp_head', 'wp_oembed_add_discovery_links');
remove_action('wp_head', 'wp_oembed_add_host_js');
 
/** 絵文字のコードを消す **/
/*------------------------------------------*/
remove_action('admin_print_scripts', 'print_emoji_detection_script');
remove_action('admin_print_styles', 'print_emoji_styles');
remove_filter('the_content_feed', 'wp_staticize_emoji');
remove_filter('comment_text_rss', 'wp_staticize_emoji');
remove_filter('wp_mail', 'wp_staticize_emoji_for_email');
remove_action('wp_head', 'print_emoji_detection_script', 7);
remove_action('wp_print_styles', 'print_emoji_styles');

デフォルトでサイト側に吐き出されるものには、不要なものも沢山ありますので、整理しておきます。

タイトルタグの区切り

/** タイトルタグの区切り **/
/*------------------------------------------*/
/**- タイトルタグをサポートさせる -**/
function mytheme_setup() {
  add_theme_support('title-tag');
}
add_action('after_setup_theme', 'mytheme_setup');
 
/**- タイトルタグからディスクリプションを削除 -**/
function remove_tagline($title) {
  if (isset($title['tagline'])) {
    unset($title['tagline']);
  }
  return $title;
}
add_filter( 'document_title_parts', 'remove_tagline' );
 
/**- タイトルタグの仕切り「-」を「|」へ変更 -**/
function my_document_title_separator($sec) {
  $sec = "|";
  return $sec;
}
add_filter('document_title_separator', 'my_document_title_separator');

タイトルタグを自動で生成するようにして、不要なコメントを削除します。
また、デフォルトでは「ページの名称 – サイトタイトル」と、区切りが「-」になりますので、
任意のもの(上記では「|」へ)変更します。

ページネーション

/** Pagination **/
/*------------------------------------------*/
function pagination($pages = '', $range = 2) {
  $showitems = ($range * 2)+1; //表示するページ数(5ページ)
 
  global $paged; //現在のページ値
  if(empty($paged)) $paged = 1; //デフォルトのページ
 
  if($pages == '') {
    global $wp_query;
    $pages = $wp_query->max_num_pages; //全ページ数を取得
    if(!$pages) { //全ページ数が空の場合は、1とする
      $pages = 1;
    }
  }
 
  if(1 != $pages) { //全ページが1でない場合は表示
 
    echo "<div class=\"pagination\">\n";
    echo "<ul>\n";
 
    //Prev:現在のページ値が1より大きい場合は表示
    if($paged > 1) echo "<li class=\"prev\"><a href='".get_pagenum_link($paged - 1)."'>Prev</a></li>\n";
 
    for ($i=1; $i <= $pages; $i++) {
      if (1 != $pages &&( !($i >= $paged+$range+1 || $i <= $paged-$range-1) || $pages <= $showitems )) {
 
        //現在のページ数と一致すればactiveクラス付与
        echo ($paged == $i)? "<li class=\"active\">".$i."</li>\n":"<li><a href='".get_pagenum_link($i)."'>".$i."</a></li>\n";
      }
    }
 
    //Next:総ページ数より現在のページ値が小さい場合
    if ($paged < $pages) echo "<li class=\"next\"><a href=\"".get_pagenum_link($paged + 1)."\">Next</a></li>\n";
    echo "</ul>\n";
    echo "</div>\n";
  }
}

ページネーションを自動作成します。
表示させるには、テンプレートファイルのループ後の任意の場所へ

<?php
if (function_exists("pagination")) {
    pagination($additional_loop->max_num_pages);
}
?>

を記載します。

また、上記のコードで生成されるhtmlは以下となります。

<div class="pagenation">
<ul>
<li class="active">1</li>
<li><a href='/page/2/'>2</a></li>
<li class="next"><a href="/page/2/">Next</a></li>
</ul>
</div>

テンプレートに持ち込んで使いまわしたい変数

/** テンプレートに持ち込んで使いまわしたい変数 **/
/*------------------------------------------*/
$tmp_dir  = get_template_directory_uri(); // テンプレートディレクトリURL
$site_url = home_url(); // ホームページURL

個人的に便利なので。
使用したいテンプレートそれぞれに、

<?php global $tmp_dir, $site_url; ?>

を忘れずに。

この他にも、作りたいサイトによっていろいろ入れてます。
それはまたの機会に~。