この記事は最後に更新してから1年以上経過しています。
説明
PC向けのサイトをスマートフォン対応する場合、WPtouchやktai styleに代表されるスマートフォン対応のテンプレート切り替えプラグインを使用するのが一般的。そういったプラグインはテンプレート切り替え以外の機能も備えており、そういった機能は必ずしも必要ではない。そんなわけで、ここでは超シンプルなスマートフォン向けのテンプレート切り替えを実現する方法を紹介する。template_includeフィルターを活用
テンプレートの振り分けを自身でコントロールする方法としては、template_includeフィルターを利用するのが手っ取り早い。具体的には、テーマ内のfunctions.phpにて、 add_filter関数を利用する。add_filter( 'template_include', 'mytheme_template_include' );
function mytheme_template_include( $template ) {
if ( is_smart_phone() ) {
$template_sp = str_replace( '.php', '-sp.php', $template );
if ( file_exists( $template_sp ) )
$template = $template_sp;
}
return $template;
}
スマートフォン判定
WordPressにはグローバル変数 $is_iphoneがあるが、Androidスマートフォンが対象にならないため、独自のスマートフォン判定を行うis_smart_phone関数を定義する。function is_smart_phone() {
return preg_match( '/android.+mobile/i', $_SERVER['HTTP_USER_AGENT'] ) ||
preg_match( '/iphone/i', $_SERVER['HTTP_USER_AGENT'] );
}
最終更新 : 2012年01月23日 19:54
関連
お勧め
wp_print_inline_script_tag(2021年4月19日 更新)
void wp_print_inline_script_tag( string $javascript [ , array $attributes = array() ] )
インラインJavaScriptを含むscript要素を出力する。
register_rest_route(2022年8月17日 更新)
bool register_rest_route( string $namespace, string $route [ , array $args = array() [ , bool $override = false ] ] )
REST APIのルートを登録する。
wp_determine_option_autoload_value(2024年7月22日 更新)
string wp_determine_option_autoload_value( string $option, mixed $value, mixed $serialized_value, boo l |string $autoload )
自動ロードのトリガー値を取得する。
single_tag_title(2018年5月27日 更新)
string single_tag_title( [ string $prefix = '' [ , bool $display = true ] ] )
投稿タグアーカイブページの投稿タグ名を取得し、パラメータ$displayがtrueならば表示する。$displayがfalseの場合は、文字列として返す。
home_url(2023年3月31日 更新)
string home_url( [ string $path = '' [ , string $scheme = null ] ] )
現在のブログ(サイト)のホームURLを取得する。ホームURLは、管理者ページの「設定」-「一般」の「サイトのアドレス(URL)」のこと。