2016.11.10
【WordPress】functions.phpで設定しておくと便利なこと
functions.phpで設定しておくと便利なことをメモメモ
▼パス設定
define( 'HOME_URI', home_url() ); define( 'THEME_URI', get_template_directory_uri() ); define( 'THEME_IMAGES', THEME_URI . '/img' ); define( 'THEME_CSS', THEME_URI . '/css' ); define( 'THEME_JS', THEME_URI . '/js' );
▼非表示設定
(参考:WordPress 本体やプラグイン、テーマの更新通知を非表示にする方法)
//admin barの非表示 add_filter( 'show_admin_bar', '__return_false' ); //本体の更新通知を非表示 add_filter('pre_site_transient_update_core', create_function('$a', "return null;")); //プラグイン更新通知を非表示 remove_action( 'load-update-core.php', 'wp_update_plugins' ); add_filter( 'pre_site_transient_update_plugins', create_function( '$a', "return null;" ) );
▼クイックタグボタンを追加
(参考:プラグイン不要!WordPressのテキストエディタにタグ挿入クイックタグボタンを追加する方法)
if ( !function_exists( 'add_quicktags_to_text_editor' ) ): function add_quicktags_to_text_editor() { //スクリプトキューにquicktagsが保存されているかチェック if (wp_script_is('quicktags')){?> <script> QTags.addButton('qt-bold','太字','<span style="font-weight:bold;">','</span>'); QTags.addButton('qt-red','赤字','<span style="color:#FF0000;">','</span>'); </script> <?php } } endif; add_action( 'admin_print_footer_scripts', 'add_quicktags_to_text_editor' );
▼スマホ判別
(参考:WordPressでスマートフォン・タブレット・PCで表示を変更する条件分岐方法)
function is_mobile(){ $useragents = array( 'iPhone', // iPhone 'iPod', // iPod touch 'Android.*Mobile', // 1.5+ Android *** Only mobile 'Windows.*Phone', // *** Windows Phone 'dream', // Pre 1.5 Android 'CUPCAKE', // 1.5+ Android 'blackberry9500', // Storm 'blackberry9530', // Storm 'blackberry9520', // Storm v2 'blackberry9550', // Storm v2 'blackberry9800', // Torch 'webOS', // Palm Pre Experimental 'incognito', // Other iPhone browser 'webmate' // Other iPhone browser ); $pattern = '/'.implode('|', $useragents).'/i'; return preg_match($pattern, $_SERVER['HTTP_USER_AGENT']); }
▼アイキャッチを有効
add_theme_support('post-thumbnails'); // アイキャッチ画像がないときに表示する画像設定 function thumbnail_check( $post_id, $size='post-thumbnail' ) { if ( has_post_thumbnail() ){ //ループ外で使うことも想定するとhas_post_thumbnail( $post_id)のほうがいいかもしれません $thumb = get_the_post_thumbnail( $post_id, $size ); } else { $thumb = '<img src="'.get_template_directory_uri().'/images/no-img.png" alt="">'; } echo $thumb; }
▼画像サイズを指定
(参考:メディアのサイズを追加する[WordPress])
//functions.phpに記載 add_image_size('img300x200', 300, 200);
//画像の表示方法 <?php if(have_posts()): while(have_posts()): the_post(); $thumbnail_id = get_post_thumbnail_id($post->ID); //アタッチメントIDの取得 $image = wp_get_attachment_image_src( $thumbnail_id, 'img300x200' ); //「img300x200」サイズのアイキャッチの情報を取得 ?> <img src="<?php echo $image[0]; ?>" alt="<?php the_title(); ?>" /> <?php endwhile;endif; ?>
▼検索結果から「ページ」を除外
function SearchFilter($query) { if ( !is_admin() && $query->is_main_query() && $query->is_search() ) { $query->set( 'post_type', 'post' ); } } add_action( 'pre_get_posts','SearchFilter' );