calendarcodediamondfacebookfingerglobalgoogleplushatenahomepagetopplainpocketrssservicetwitterwordpresshome2searchfoldernext-arrowback-arrowfirst-arrowlast-arrow

WordPressのfunctions.phpに書いておくと捗ること

WordPressにfunctions.phpに書いておくと捗ることをまとめておきます。

PR
IT/WEB業界への転職なら
Sponsored Link

固定ページ判別。bodyに固定ページのスラッグ名を追加

bodyに固定ページのスラッグ名を追加。トップページはhomeのクラス名がつく。固定ページなどはguide aboutなどのスラッグ名を取得しクラス名が付与される。

01
02
03
04
05
06
07
08
function pagename_class($classes = ''){
  if (is_page()) {
    $page = get_post();//get_page()は廃止されたので使わない
    $classes[] = $page->post_name;//スラッグ名取得
  }
  return $classes;
}
add_filter('body_class', 'pagename_class');

呼び出し

01
<body <?php body_class( $class ); ?>>

テンプレートタグ/body class - WordPress Codex 日本語版

WordPressの body_class()にページスラッグの決定版 | terabenote.net

ブラウザ判別。bodyにブラウザ名付与

これをつけておくと、ブラウザごとにスタイル等を制御できるので便利。

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
add_filter('body_class','browser_body_class');
function browser_body_class($classes) {
    global $is_lynx, $is_gecko, $is_IE, $is_opera, $is_NS4, $is_safari, $is_chrome, $is_iphone;
 
    if($is_lynx) $classes[] = 'lynx';
    elseif($is_gecko) $classes[] = 'gecko';
    elseif($is_opera) $classes[] = 'opera';
    elseif($is_NS4) $classes[] = 'ns4';
    elseif($is_safari) $classes[] = 'safari';
    elseif($is_chrome) $classes[] = 'chrome';
    elseif($is_IE) $classes[] = 'ie';
    else $classes[] = 'unknown';
 
    if($is_iphone) $classes[] = 'iphone';
    return $classes;
}

Browser Detection and the body_class() Function

アップロードした画像を特定のサイズにリサイズする

01
02
add_theme_support('post-thumbnails');
add_image_size( 'trimming_600_400', 600, 400, true );

呼び出し

01
<?php the_post_thumbnail('trimming_600_400'); ?>

admin バー 非表示

01
add_filter('show_admin_bar', '__return_false');

ページタイトルを自動出力

WordPress4.1でタイトルタグが追加されましたが、以下のタグをfunctions.phpに記述すると、現在非推奨のwp_title関数を使わずにタイトルを出力することができます。

01
add_theme_support( 'title-tag' );

セパレーターなど細かなカスタマイズ方法は以下に詳しく書かれてます。

WordPress4.4以降でtitleタグをカスタマイズする方法 | Glatch(グラッチ) – 夫婦で活動するフリーランスWeb制作ユニット

JavaScriptをフッターに移動

JavaScriptは基本的にheadで読み込まず、できるだけbodyの下部で読み込むようにしたいので、function.phpに以下のように記載。そうすると後からJavaScriptの処理をさせるので体感的にユーザーが遅く感じにくくなります。パラメーターをtrueにすることでwp_footer()で読み込まれます。trueでbody終了タグの前、falseでhead前。

01
02
03
04
05
06
07
08
09
10
11
12
// trueでbody終了タグの前、falseでhead前
function register_jquery(){
wp_enqueue_script(
'common-js',
get_template_directory_uri() . '/js/common.js',
array(),
NULL,
true
);
wp_enqueue_script( 'common-js' );
}
add_action('wp_enqueue_scripts', 'register_jquery');

ウィジェット登録

01
02
03
04
05
06
07
08
register_sidebar(array(
  'name'         => __('widget1'),
  'id'           => 'widget1',
  'before_widget'=> '',
  'after_widget' => '',
  'before_title' => '',
  'after_title'  => '',
));

呼び出し

01
<?php dynamic_sidebar('widget1' ); ?>

プラグイン・WordPress自動更新

01
02
03
04
05
06
07
08
//プラグインの自動更新を有効化
add_filter( 'auto_update_plugin', '__return_true' );
//テーマの自動更新を有効化
add_filter( 'auto_update_theme', '__return_true' );
//メジャーアップグレードの自動更新を有効化
add_filter( 'allow_major_auto_core_updates', '__return_true' );
//マイナーアップグレードの自動更新を有効化
add_filter( 'allow_minor_auto_core_updates', '__return_true' );

不要な読み込みを減らして軽くする

WordPressバージョン情報を記載しておく理由などないし、Windows用のWordPressツールも使わないので削除しておきます。

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
// WordPressのバージョン情報は削除したほうがいい
remove_action('wp_head', 'wp_generator');
// ブログ投稿ツール用
remove_action('wp_head', 'rsd_link');
// Windows Live Writerは使わないので削除
remove_action('wp_head', 'wlwmanifest_link');
// Embed WPのブログカード。他サイトのアイキャッチ画像や抜粋自動埋め込み
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');
// 管理画面絵文字削除
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');

概要(抜粋)の文字数調整

01
02
03
04
function my_excerpt_length($length) {
    return 80;
}
add_filter('excerpt_length', 'my_excerpt_length');

文末の[…]を削除し、...にする

01
02
03
04
function my_excerpt_more($more) {
    return '...';
}
add_filter('excerpt_more', 'my_excerpt_more');

コメント欄のメール削除し、コールバック関数を追加

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
// コメント ウェブサイトの入力欄を消す
add_filter('comment_form_default_fields', 'mytheme_remove_url');
function mytheme_remove_url($arg) {
$arg['url'] = '';
return $arg;
}
  
// コメント フォーム内のURLオートリンクを停止する
remove_filter('comment_text', 'make_clickable');
  
// コメント カスタマイズ コールバック関数
function mytheme_comment($comment, $args, $depth) {
    if ( 'div' === $args['style'] ) {
        $tag       = 'div';
        $add_below = 'comment';
    } else {
        $tag       = 'li';
        $add_below = 'div-comment';
    }
    ?>
    <<?php echo $tag ?> <?php comment_class( empty( $args['has_children'] ) ? '' : 'parent' ) ?> id="comment-<?php comment_ID() ?>">
    <?php if ( 'div' != $args['style'] ) : ?>
        <div id="div-comment-<?php comment_ID() ?>" class="comment-body">
    <?php endif; ?>
  
        <!-- 日付 -->
        <div class="comment-meta commentmetadata"><a href="<?php echo htmlspecialchars( get_comment_link( $comment->comment_ID ) ); ?>">
            <?php
            /* translators: 1: date, 2: time */
            printf( __('%1$s at %2$s'), get_comment_date(),  get_comment_time() ); ?></a><?php edit_comment_link( __( '(Edit)' ), '  ', '' );
            ?>
        </div>
  
        <!-- アバター -->
        <div class="flex">
            <div class="comment-author vcard">
                <?php if ( $args['avatar_size'] != 0 ) echo get_avatar( $comment, $args['avatar_size'] ); ?>
            </div>
            <?php if ( $comment->comment_approved == '0' ) : ?>
                <em class="comment-awaiting-moderation"><?php _e( 'Your comment is awaiting moderation.' ); ?></em>
                <br />
            <?php endif; ?>
            <!-- 内容 -->
            <div class="comment-content">
                <?php printf( __( '<cite class="fn">%s</cite>' ), get_comment_author_link() ); ?>
                <?php comment_text(); ?>
            </div>
        </div>
  
        <!-- 返信ボタン -->
    <div class="reply">
        <?php comment_reply_link( array_merge( $args, array( 'add_below' => $add_below, 'depth' => $depth, 'max_depth' => $args['max_depth'] ) ) ); ?>
    </div>
    <?php if ( 'div' != $args['style'] ) : ?>
    </div>
    <?php endif; ?>
    <?php
    }

参考:WordPress コメント入力欄をカスタマイズしてウェブサイト(URL)やメールアドレスを簡単に消す方法 | debate

以上、functions.phpに書いておきたいことでした。

スポンサード リンク

この記事を書いた人
投稿者:commte

株式会社コムテ代表取締役。2015/8:弊社にてWeb制作スクールを開始。 WebDesign + Web制作 (最新情報 配信)。おっとりした話し方をするおっさん。

URL:西田 鉄平
この後によく読まれている記事

Comments

Leave a Comment

コメントする