WordPress代码判断移动端 让手机站样式独具风格

  • 2020-12-28 20:30:35
  • 1,919 次阅读
  • 稿源:天马行空

wordpress制作自适应网站,通过媒体查询功能,判断当前设备屏幕大小,显示模版不同的样式。这样就可以使用一个模版实现pc端,ipad端和移动端的切换。但是,如果想实现pc端和移动端是独立的两套模版,也就说在修改pc端某个css样式时,手机端的样式不受影响,换句话就是pc端和移动端的css样式互不干扰。这样就需要WordPress代码判断手机移动设备,然后再跳转到手机端。

WordPress代码判断移动端 让手机站样式独具风格

WordPress使用纯代码判断当前设备并跳转到手机端,步骤如下:

第一步,在主题functions.php中加入下列代码 ,基本上是常见的移动浏览器的useragent。

function is_mobile() {
    $user_agent = $_SERVER['HTTP_USER_AGENT'];
    $mobile_browser = Array(
        "mqqbrowser", //手机QQ浏览器
        "opera mobi", //手机opera
        "juc","iuc",//uc浏览器
        "fennec","ios","applewebKit/420","applewebkit/525","applewebkit/532","ipad","iphone","ipaq","ipod",
        "iemobile", "windows ce",//windows phone
        "240x320","480x640","acer","android","anywhereyougo.com","asus","audio","blackberry","blazer","coolpad" ,"dopod", "etouch", "hitachi","htc","huawei", "jbrowser", "lenovo","lg","lg-","lge-","lge", "mobi","moto","nokia","phone","samsung","sony","symbian","tablet","tianyu","wap","xda","xde","zte"
    );
    $is_mobile = false;
    foreach ($mobile_browser as $device) {
        if (stristr($user_agent, $device)) {
            $is_mobile = true;
            break;
        }
    }
    return $is_mobile;
}

第二步,如果想制作index.php首页模版,使用下列代码判断

<?php if( !is_mobile() ){ ?>

pc端index.php

<?php } else{ ?>

<?php get_template_part("indexForMobile");?>

<?php } ?>

第三步,如果想制作single.php模版页,使用如下:

<?php if( !is_mobile() ){ ?>
// pc端single.php
<?php } else{ ?>

<?php get_template_part("singleForMobile");?>

<?php } ?>

补充参考:手机端可能用到的代码

//面包屑
function fairy_breadcrumbs() {
	$delimiter = '»';
	$home = '首页'; 
	$before = '<span>'; 
	$after = '</span>'; 
	if ( !is_home() && !is_front_page() || is_paged() ) {
		echo '<div id="crumbs">';
		global $post;
		$homeLink = get_bloginfo('url');
		echo '<a href="' . $homeLink . '">' . $home . '</a> ' . $delimiter . ' ';
		if ( is_category() ) {
			global $wp_query;
			$cat_obj = $wp_query->get_queried_object();
			$thisCat = $cat_obj->term_id;
			$thisCat = get_category($thisCat);
			$parentCat = get_category($thisCat->parent);
			if ($thisCat->parent != 0) echo(get_category_parents($parentCat, TRUE, ' ' . $delimiter . ' '));
			echo $before . ' "' . single_cat_title('', false) . '" 目录下的文章' . $after;
		} else if ( is_single() && !is_attachment() ) {
			if ( get_post_type() != 'post' ) {
				$post_type = get_post_type_object(get_post_type());
				$slug = $post_type->rewrite;
				echo '<a href="' . $homeLink . '/' . $slug['slug'] . '/">' . $post_type->labels->singular_name . '</a> ' . $delimiter . ' ';
				echo $before . get_the_title() . $after;
			} else {
				$cat = get_the_category(); $cat = $cat[0];
				echo get_category_parents($cat, TRUE, ' ' . $delimiter . ' ');
				echo $before . get_the_title() . $after;
			}
		} else if ( !is_single() && !is_page() && get_post_type() != 'post' ) {
			$post_type = get_post_type_object(get_post_type());
			echo $before . $post_type->labels->singular_name . $after;
		}
		if ( get_query_var('paged') ) {
			if ( is_category() || is_day() || is_month() || is_year() || is_search() || is_tag() || is_author() ) echo ' (';
				echo __('Page') . ' ' . get_query_var('paged');
				if ( is_category() || is_day() || is_month() || is_year() || is_search() || is_tag() || is_author() ) echo ')';
	}
	echo '</div>';
	}
} 
//上下一页
function xiayiye( $before = '', $after = '', $p = 2 ) {
	if ( is_singular() ) return;
	global $wp_query, $paged;
	$max_page = $wp_query->max_num_pages;
	if ( $max_page == 1 ) return;
	if ( empty( $paged ) ) $paged = 1;
	echo $before.'<div><ul>'."\n";
	//echo '<span>Page: ' . $paged . ' of ' . $max_page . ' </span>';
	if ( $paged > 1 ) p_link( $paged - 1, '上一页', '上一页' );
	//if ( $paged > $p + 2 ) echo ' ';
	//if ( $paged < $max_page - $p - 1 ) echo '... ';
	if ( $paged < $max_page ) p_link( $paged + 1,'下一页', '下一页' );
	echo '</ul></div>'.$after."\n";
} 
//自动关键词
function auto_keywords() {
	global $s, $post;
	$keywords = '';
	if ( is_single() ) {
		if ( get_the_tags( $post->ID ) ) {
			foreach ( get_the_tags( $post->ID ) as $tag ) $keywords .= $tag->name . ', ';
		}
		foreach ( get_the_category( $post->ID ) as $category ) $keywords .= $category->cat_name . ', ';
		$keywords = substr_replace( $keywords , '' , -2);
	} elseif ( is_home () ) { 
		$keywords = '首页关键词,需要自己填写在这里';
	} elseif ( is_tag() ) { 
		$keywords = single_tag_title('', false);
	} elseif ( is_category() ) { 
		$keywords = single_cat_title('', false);
	} elseif ( is_search() ) { 
		$keywords = esc_html( $s, 1 );
	} else { 
		$keywords = trim( wp_title('', false) );
	}
	if ( $keywords ) {
		echo '<meta name="keywords" content="'.$keywords.'" />\n';
	}
} 
//自动描述
function auto_description() {
	global $s, $post;
	$description = '';
	$blog_name = get_bloginfo('name');
	if ( is_singular() ) {
		if( !empty( $post->post_excerpt ) ) {
			$text = $post->post_excerpt;
		} else {
			$text = $post->post_content;
		}
		$description = trim( str_replace( array( "\r\n", "\r", "\n", " ", " "), " ", str_replace( "\"", "'", strip_tags( $text ) ) ) );
		if ( !( $description ) ) $description = $blog_name . " - " . trim( wp_title('', false) );
	} elseif ( is_home () ) { 
		$description = $blog_name . " - 首页描述,需要自己填写在这里"; // 首頁要自己加
	} elseif ( is_tag() ) { 
		$description = $blog_name . "有关 '" . single_tag_title('', false) . "' 的文章";
	} elseif ( is_category() ) { 
		$description = $blog_name . "有关 '" . single_cat_title('', false) . "' 的文章";
	} elseif ( is_archive() ) { 
		$description = $blog_name . "在: '" . trim( wp_title('', false) ) . "' 的文章";
	} elseif ( is_search() ) { 
		$description = $blog_name . ": '" . esc_html( $s, 1 ) . "' 的搜索結果";
	} else { 
		$description = $blog_name . "有关 '" . trim( wp_title('', false) ) . "' 的文章";
	}
	$description = mb_substr( $description, 0, 220, 'utf-8' ) . '..';
 
	echo '<meta name="description" content="'.$description.'" />\n';
}
//判断移动设备
function is_mobile() {
	$user_agent = $_SERVER['HTTP_USER_AGENT'];
	$mobile_agents = Array("240x320","acer","acoon","acs-","abacho","ahong","airness","alcatel","amoi","android","anywhereyougo.com","applewebkit/525","applewebkit/532","asus","audio","au-mic","avantogo","becker","benq","bilbo","bird","blackberry","blazer","bleu","cdm-","compal","coolpad","danger","dbtel","dopod","elaine","eric","etouch","fly ","fly_","fly-","go.web","goodaccess","gradiente","grundig","haier","hedy","hitachi","htc","huawei","hutchison","inno","ipad","ipaq","ipod","jbrowser","kddi","kgt","kwc","lenovo","lg ","lg2","lg3","lg4","lg5","lg7","lg8","lg9","lg-","lge-","lge9","longcos","maemo","mercator","meridian","micromax","midp","mini","mitsu","mmm","mmp","mobi","mot-","moto","nec-","netfront","newgen","nexian","nf-browser","nintendo","nitro","nokia","nook","novarra","obigo","palm","panasonic","pantech","philips","phone","pg-","playstation","pocket","pt-","qc-","qtek","rover","sagem","sama","samu","sanyo","samsung","sch-","scooter","sec-","sendo","sgh-","sharp","siemens","sie-","softbank","sony","spice","sprint","spv","symbian","tablet","talkabout","tcl-","teleca","telit","tianyu","tim-","toshiba","tsm","up.browser","utec","utstar","verykool","virgin","vk-","voda","voxtel","vx","wap","wellco","wig browser","wii","windows ce","wireless","xda","xde","zte");
	$is_mobile = false;
	foreach ($mobile_agents as $device) {
		if (stristr($user_agent, $device)) {
			$is_mobile = true;
			break;
		}
	}
	return $is_mobile;
}
//统计浏览次数
function getPostViews($postID){
	$count_key = 'post_views_count';
	$count = get_post_meta($postID, $count_key, true);
	if($count==''){
		delete_post_meta($postID, $count_key);
		add_post_meta($postID, $count_key, '0');
		return 0;
	}
	return $count;
}
 
function setPostViews($postID) {
	$count_key = 'post_views_count';
	$count = get_post_meta($postID, $count_key, true);
	if($count==''){
		$count = 0;
		delete_post_meta($postID, $count_key);
		add_post_meta($postID, $count_key, '0');
	}else{
		$count++;
		update_post_meta($postID, $count_key, $count);
	}
}
喜欢 0

文章评论 (0)

表情

大眼 可爱 大笑 坏笑 害羞 发怒 折磨 快哭了 大哭 白眼 晕 流汗 困 腼腆 惊讶 憨笑 色 得意 骷髅 囧 睡觉 眨眼 亲亲 疑问 闭嘴 难过 淡定 抗议 鄙视 猪头