2021最新版、WordPressでサイトでもブログでも流用できるfunctions.php

2021最新版、WordPressでサイトでもブログでも流用できるfunctions.php

WordPressオリジナルテーマでサイトを制作する時に、めっちゃ使いそうなfunctions.phpをメモ。
これがあるとサイトでもブログでも流用できるから便利♪

functions.phpとは?

テーマを作成する際に使用するファイルの1つ。
現在有効なテーマのディレクトリにあり、実行され、そのテーマに対してのみ機能する。

出来ることは以下のようなこと

    function.phpができること

  • テーマ内で使う関数の定義
  • ショートコードの定義
  • 管理画面の設定
  • 関数、グローバル変数、クラスを定義
  • フィルタ・アクション関数の定義
    具体例

  • ログイン画面をカスタマイズ
  • ショートコードを作る
  • ツールバーの非表示
  • アイキャッチ画像の有効化
  • ナビゲーションメニューの有効化

functions.phpがある場所

インストールディレクトリ / wp-content / themes / テーマフォルダ / functions.php

▼参考リンク:
functions.php 概説 – WordPress Codex 日本語版

コピペ用 functions.php

<?php

// JS・CSSファイルを読み込む
function add_files() {
	// WordPress提供のjquery.jsを読み込まない
	wp_deregister_script('jquery');

	// jQueryの読み込み
	wp_enqueue_script( 'jquery', '//ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js', "", "20160608", false );

	// サイト共通JS
	wp_enqueue_script( 'my-script', get_template_directory_uri() . '/js/main.js', array( 'jquery' ), '20160608', true );

	// サイト共通のCSSの読み込み
	wp_enqueue_style('bootstrap-css',get_template_directory_uri().'/bs/css/bootstrap.min.css' );
	wp_enqueue_style('fontawesome',get_template_directory_uri().'/fontawesome/css/all.min.css');
	wp_enqueue_style( 'main', get_template_directory_uri() . '/style.css', "", '20160608' );
}
add_action('wp_enqueue_scripts', 'add_files');



// カスタムメニューを有効化
add_theme_support( 'menus' );



// カスタムメニューの「場所」を設定
register_nav_menu( 'header-navi', 'ヘッダーのナビゲーション' );
register_nav_menu( 'd-navi', 'ドロワーのナビゲーション' );



// サイドバーウィジットを有効化
register_sidebar( array(
	'name' => 'サイドバーウィジット-1',
	'id' => 'sidebar-1',
	'description' => 'サイドバーのウィジットエリアです。',
	'before_widget' => '<div id="%1$s" class="widget %2$s">',
	'after_widget' => '</div>',
	'before_title' => '<h3 class="widget-title">',
	'after_title' => '</h3>',
) );



// タイトルタグ出力
function mytheme_set() {
  add_theme_support( 'title-tag' );
}
add_action( 'after_setup_theme', 'mytheme_set' );



// アイキャッチ画像の有効化
add_theme_support('post-thumbnails');



// 検索をHTML5形式に
function mytheme_setup() {
    add_theme_support( 'html5', array(
        'search-form',
    ) );
}
add_action( 'after_setup_theme', 'mytheme_setup' );



// パンくずリスト
function breadcrumb() {
	echo '<ul>';
	//HOME>と表示
	$sep = '/';
	echo '<li><a href="'.get_bloginfo('url').'" >HOME</a></li>';
	echo $sep;

	//投稿記事ページとカテゴリーページでの、カテゴリーの階層を表示
	$cats = '';
	$cat_id = '';
	if ( is_single() ) {
		$cats = get_the_category();
		if( isset($cats[0]->term_id) ) $cat_id = $cats[0]->term_id;
	}
	else if ( is_category() ) {
		$cats = get_queried_object();
		$cat_id = $cats->parent;
	}
	$cat_list = array();
	while ($cat_id != 0){
		$cat = get_category( $cat_id );
		$cat_link = get_category_link( $cat_id );
		array_unshift( $cat_list, '<a href="'.$cat_link.'">'.$cat->name.'</a>' );
		$cat_id = $cat->parent;
	}
	foreach($cat_list as $value){
		echo '<li class="cat-name">'.$value.'</li>';
		echo $sep;
	}

	//現在のページ名を表示
	if ( is_singular() ) {
		if ( is_attachment() ) {
			previous_post_link( '<li>%link</li>' );
			echo $sep;
		}
		the_title( '<li class="post-title">', '</li>' );
	}

	else if( is_archive() ) the_archive_title( '<li class="current-name">', '</li>' );
	else if( is_search() ) echo '<li>検索 : '.get_search_query().'</li>';
	else if( is_404() ) echo '<li>ページが見つかりません</li>';

	echo '</ul>';
}



/* the_archive_title 余計な文字を削除 */
add_filter( 'get_the_archive_title', function ($title) {
    if (is_category()) {
        $title = single_cat_title('',false);
    } elseif (is_tag()) {
        $title = single_tag_title('',false);
	} elseif (is_tax()) {
	    $title = single_term_title('',false);
	} elseif (is_post_type_archive() ){
		$title = post_type_archive_title('',false);
	} elseif (is_date()) {
	    $title = get_the_time('Y年n月');
	} elseif (is_search()) {
	    $title = '検索結果:'.esc_html( get_search_query(false) );
	} elseif (is_404()) {
	    $title = '「404」ページが見つかりません';
	} else {

	}
    return $title;
});



// 投稿にカスタムタクソノミーを追加
add_action('init', 'register_blog_cat_custom_post');
function register_blog_cat_custom_post() {
    register_taxonomy(
        'event-cat',
        'post',
        array(
            'hierarchical' => true,
            'label' => 'イベント商材名',
            'show_ui' => true,
            'query_var' => true,
            'rewrite' => true,
            'singular_label' => 'イベント商材のカテゴリ'
        )
    );
}



//YOUTUBE動画の埋め込みコードを自動的にdivタグで囲む
function iframe_in_div($the_content) {
if ( is_singular() ) {
$the_content = preg_replace('/<iframe/i', '<div class="youtube"><iframe', $the_content);
$the_content = preg_replace('/<\/iframe>/i', '</iframe></div>', $the_content);
}
return $the_content;
}
add_filter('the_content','iframe_in_div');



// 検索結果に固定ページを表示させない
function mycus_search_filter_post_only_func( $query ) {
    if ( $query->is_search() && $query->is_main_query() && ! $query->is_admin() ) {
        $query->set( 'post_type', 'post' );
    }
    return $query;
}
add_filter( 'pre_get_posts', 'mycus_search_filter_post_only_func' );



///////////////////////////

// 非表示関連

///////////////////////////
// WordPressバージョン出力metaタグ非表示
remove_action('wp_head','wp_generator');

// 外部ツールの編集用URLの非表示
remove_action('wp_head', 'rsd_link');

// Windows Live Writerの編集用URLの非表示
remove_action('wp_head', 'wlwmanifest_link');

//現在の文書に対する「索引」であることを示すタグ
remove_action( 'wp_head', 'index_rel_link' );

// 絵文字機能の削除
function disable_emoji() {
 remove_action( 'wp_head', 'print_emoji_detection_script', 7 );
 remove_action( 'admin_print_scripts', 'print_emoji_detection_script' );
 remove_action( 'wp_print_styles', 'print_emoji_styles' );
 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' );
}
add_action( 'init', 'disable_emoji' );

// adminbarの非表示
function disable_admin_bar(){
  return false;
}
add_filter( 'show_admin_bar' , 'disable_admin_bar');

// Gutenberg用のCSSファイルを非表示
add_action('wp_enqueue_scripts', 'remove_block_library_style');
function remove_block_library_style(){
   wp_dequeue_style('wp-block-library');
   wp_dequeue_style('wp-block-library-theme');
}

// wp-embed.min.js の削除
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');

// HTTPレスポンス成形
remove_action('template_redirect', 'rest_output_link_header', 11 );

// skip-link-focus-fix.js の削除
wp_enqueue_script( 'sparkling-skip-link-focus-fix', get_template_directory_uri() . '/inc/js/skip-link-focus-fix.js', array(), '20140222', true );

// Related Posts modern.css の読み込み禁止
add_action( 'wp_enqueue_scripts', 'deregister_plugin_files' );
function deregister_plugin_files() {
        wp_dequeue_style( 'wp_rp_edit_related_posts_css' );
}

?>

制作対応できるのは

202311月〜

ご相談はいつでもOK!

東京ブランド「ロゴ」