LoginSignup
5

More than 5 years have passed since last update.

wordpress関連のコード【自分用のストック】

Last updated at Posted at 2015-03-31

Wordpressで「あれ、こういう時どうやるんだっけ?」となることが多いので忘備録として記述
wordpress関連は探せばいくらでも出てくるので他にも方法はあると思います。
何はともあれ、情報を上げてくれている人には感謝です。
詳しくはリンク先で。

※思いついたら書きためていくので、順次追加予定です。

functions.phpで他のファイルを読み込む

やっぱり、つらつらfunctions.phpの中身に書いていくと、肥大化しやすく管理もしにくくなるので、functions.phpの中身は別のファイルを読み込むようにする。
中身を以下のように変更する。

functions.php
<?php
    // []は不要でpathを記述
    locate_template('[filepath]', true);

あとは読み込むファイルの数だけ、上記の記述を書いていく。

function.phpからjsの読み込みを行う

wordpressでthemeを作ってると、特定のページだけこのjs読ませたいんだよなぁ...みたいなことがある。
footer.phpに条件分岐で読み込ませれば解決できるけれども、header.phpfooter.phpにずらずら書きたくない。htmlとして出力してしまえば結果は変わらないけれど、htmlの中にphpをだらだら書くと可読性が落ちると思うので、funciton.phpで管理する。

function-libというディクレクトリの中にscript.phpというファイルを作成した。
functions.phpには以下の内容を追記して作成したファイルを読み込むようにする。

funcitons.php
    locate_template('function-libs/script.php', true);
script.php
<?php
    // 管理画面ではこの処理を行わない
    if (!is_admin()){

        function register_script() {
            // デフォルトのjQueryは読み込まない
            wp_deregister_script('jquery');
            // cdnでjQeryを呼び出す
            wp_register_script('jquery', '//cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js', '', true, true);
            // 独自のjs
            wp_register_script('default', get_template_directory_uri() . '/js/application.js', '', true, true);

        }

        function add_script() {
            register_script();
                wp_enqueue_script('jquery');
                wp_enqueue_script('default');
        }

        add_action('wp_print_scripts', 'add_script');

    }

wp_register_script()の第5引数はデフォルトではfalseになっていて、これがfalseだと<head>~</head>の間で読み込まれ、trueだと</body>直前で読み込まれる。

function.phpからcssの読み込みを行う

jsと同じようにcssもfunctions.phpで管理する。

funcitons.php
    locate_template('function-libs/stylesheet.php', true);
stylesheet.php
<?php

    function register_style() {
        wp_register_style('libs', get_template_directory_uri() .'/css/libs.css');
        wp_register_style('style', get_template_directory_uri() .'/style.css');
    }

    function add_stylesheet() {
        register_style();
            wp_enqueue_style('libs');
            wp_enqueue_style('style');
    }

    add_action('wp_print_styles', 'add_stylesheet');

titleタグをfunctions.phpから出力させる

function.php
add_theme_support('title-tag');

function.phpに上記を記述するだけで、ページにあったtitleが出力される。

ちなみに前はこう書いていた

heade.php
<title><?php wp_title('|', true, 'right'); ?><?php bloginfo(`name`); ?></title>

body_class( )にslugを追加する

wordpressをいじっていると、ページごとに違うデザインを反映したい時がある。
というか、それがデフォルトな気がするのでメモ。
カテゴリーごとにテンプレートを作ってしまうって方法も有りだと思うけれど
その辺はケースバイケースだと思います。(新しいphpファイル作るの面倒なんて言ってない)

header.php
<body <?php body_class(); ?>>
functions.php
function pagename_class($classes = '') {
    if (is_page()) {
        $page = get_page(get_the_ID());
        $classes[] = 'page-' . $page->post_name;
        if ($page->post_parent) {
            $classes[] = 'page-' . get_page_uri($page->post_parent) . '-child';
       }
  }
  return $classes;
}
add_filter('body_class', 'pagename_class');

これでbodyにslug名も出力されるようになる。

参考 : http://terabenote.net/archives/1712/

固定ページの拡張子を.htmlに変更する

プラグインを使えばこういうのも1発でできると思いますが、
プラグイン無しで実現できるならプラグイン無しの方が良いですよね、多分。
僕はどうしても出来ないものに関してはプラグインを使いますが、
できるだけプラグインは入れたくない派です。

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 );
    }
}

参考(http://elearn.jp/wpman/column/c20120808_01.html)[http://elearn.jp/wpman/column/c20120808_01.html]

ログインユーザー別でメニュー表示を制限する

これはあまり使う機会があるのかどうか微妙なところですが
勝手にテーマの内容などをいじられたくない時に

functions.php
//-------------------------------------------------------------
//ログインツーザーが editor or contributor の時以下のメニューを非表示
//-------------------------------------------------------------
function remove_menus () {
   if ( current_user_can('editor') //ユーザーの種類をここに書く
 || current_user_can('author')
 || current_user_can('contributor')
 || current_user_can('subscriber')
    ) {

      global $menu;
      $restricted = array(
                      __('固定ページ'),//表示したくないメニューの名前
                      __('コメント'),
                      __('外観'),
                      __('プラグイン'),
                      __('ユーザー'),
                      __('ツール'),
                      __('設定'),
                      __('ユーザー管理'),
              __('お問い合わせ'),
                     );
      end ($menu);
      while (prev($menu)){
         $value = explode(' ',$menu[key($menu)][0]);
         if(in_array($value[0] != NULL?$value[0]:"" , $restricted)){unset($menu[key($menu)]);}
      }
   }
}


add_action('admin_menu', 'remove_menus');

上記の場合だと、admin以外でログインした場合はarrayの中に書いてある
メニューは消える。

年別アーカイブの数字にの表記をつける

年別アーカイブを作成したら西暦が4桁で表示されるだけで、の表記がつかなかった。
以下をfunction.phpに追記した

function.php
function add_nen_year_archives($link_html){
    $regex = array (
        "/ title='([\d]{4})'/"  => " title='$1年'",
        "/ ([\d]{4}) /"         => " $1年 ",
        "/>([\d]{4})<\/a>/"     => ">$1年</a>"
    );
    $link_html = preg_replace(array_keys($regex), $regex, $link_html);
    return $link_html;
}
add_filter('get_archives_link', 'add_nen_year_archives');

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5