WordPressのテーマSANGOでは、追尾バーは通常PCでしか表示されない設定になっています。ここでは、タブレットでも追尾バーを出したい!という時の方法をご紹介します。
という意味になるのですが、今回はPCとタブレットをセットにしたいので、スマホのみに適応させる
となります。この設定を実装するために、子テーマのfunctions.phpに以下のコードを入れてください。

PC・タブレット・スマホの分岐を設定
ポイントは、WordPress関数のwp_is_mobile()
にあります。
wp_is_mobile()
→スマホとタブレットからのアクセスに適応!wp_is_mobile()
→(前に!が付くことで逆の意味)スマホとタブレット以外、つまりPCからのアクセスに適応is_mobile()
という関数を作って対応します。is_mobile()
→スマホからのアクセスに適応!is_mobile()
→(前に!が付くことで逆の意味)スマホ以外、つまりPC・タブレットからのアクセスに適応 function php
function is_mobile() {
$useragents = array(
'iPhone',
'iPod',
'Android',
'dream',
'CUPCAKE',
'blackberry9500',
'blackberry9530',
'blackberry9520',
'blackberry9550',
'blackberry9800',
'webOS',
'incognito',
'webmate'
);
$pattern = '/'.implode('|', $useragents).'/i';
return preg_match($pattern, $_SERVER['HTTP_USER_AGENT']);
}
サイドバーのphpを修正
次にサイドバーのphpを書き換えます。sidebar.phpを子テーマにコピーして、その中の13行目あたりにある次の項目を下のように書き換えてください。
sidebar php
<?php if(is_singular() && !wp_is_mobile() && is_active_sidebar( 'fixed_sidebar' )) ://追尾のサイドバー ?>

sidebar php
つまり<?php if(is_singular() && !is_mobile() && is_active_sidebar( 'fixed_sidebar' )) ://追尾のサイドバー ?>
!wp_is_mobile()
の部分を!is_mobile()
にするだけです。修正した追尾バーのphpを追加
最後に、子テーマのfunctions.phpに以下のコードをさらに追加してください。
function php
このphpコードは、もともとSANGOのテーマフォルダの中の「library」>「functions」に入っている「sng-functions.php」にある記述です。ここでも、その中のfunction fixed_sidebar_js()
{
global $post;
if (is_singular() //投稿or固定ページ
&& !is_mobile() //PCとタブレットで表示
&& is_active_sidebar('fixed_sidebar') //固定サイドバーがアクティブ
&& !get_post_meta($post->ID, 'one_column_options', true) //1カラムオプションでない
&& !is_page_template('page-1column.php') //1カラムの固定ページでない
&& !is_page_template('page-forfront.php') //トップページ用固定ページでない
) {
echo <<< EOM
<script>
$(function(){
var fixed = $('#fixed_sidebar'),
beforefix = $('#notfix'),
main = $('#main'),
beforefixTop = beforefix.offset().top,
fixTop = fixed.offset().top,
mainTop = main.offset().top,
w = $(window);
var adjust = function(){
var fixHeight = fixed.outerHeight(true),
fixWidth = fixed.outerWidth(false),
beforefixHeight = beforefix.outerHeight(true),
mainHeight = main.outerHeight(),
winHeight = w.height(),
scrollTop = w.scrollTop(),
fixIdleBottom = winHeight + (scrollTop - mainHeight - mainTop);
if(fixTop + fixHeight < mainTop + mainHeight) {
if(scrollTop + fixHeight > mainTop + mainHeight){
fixed.removeClass('sidefixed');
fixed.addClass('sideidled');
fixed.css({'bottom':fixIdleBottom});
} else if(scrollTop >= fixTop - 25){
fixed.addClass('sidefixed');
fixed.css({'width':fixWidth,'bottom':'auto'});
} else {
fixed.removeClass('sidefixed sideidled');
fixTop = fixed.offset().top;
}
}
}
w.on('scroll', adjust);
});
</script>
EOM;
}
}
add_action('wp_footer', 'fixed_sidebar_js', 100);
!wp_is_mobile()
を!is_mobile()
に変えただけという形になります。また、このコードの中の、//固定サイドバーがアクティブ
、//トップページ用固定ページでない
などの項目についても、自分でアレンジすることで、条件を変更して追尾バーを出すことができます。
