2013-03-07 102 views
1

Im在Wordpress安裝中使用Serbanghita's PHP Mobile Detect類。我已經在我的header.php文件中以下內容:PHP Mobile Detect Wordpress

<?php 
include 'php/Mobile_Detect.php'; 
$detect = new Mobile_Detect(); 
?> 

當我把我的single.php文件裏面下面我接到一個電話在非對象錯誤:

<?php if ($detect->isMobile()) { 
     //Do something 
} ?> 

任何想法?我無法將include包括到我的single.php文件中,因爲我需要在header.php中使用它,當然我不能將它複製到single.php文件中,因爲那樣我就會聲明類。

任何幫助,非常感謝。

+0

而不是你可以使用這個wordpress內置函數wp是mobile http://codex.wordpress.org/Function_Reference/wp_is_mobile – 2013-03-07 07:28:02

回答

1

$ detect變量在文件single.php的範圍內不可用。

要麼使用全球$檢測或先定義調用$ $檢測檢測=新Mobile_Detect();

雖然我應該警告你,污染全球範圍是非常容易產生錯誤和強烈沮喪。至少要儘量減少全局變量的數量(例如,在一個類中包裝功能?),使用一個唯一的名稱(例如,前綴)或甚至更好地使用像工廠類這樣的高級技術。

+0

答案是首先讓$ detect一個全局變量(用於所有的各種php文件)。 <?php include'php/Mobile_Detect.php'; global $ detect; $ detect = new Mobile_Detect(); ?> – user1385827 2013-03-07 07:46:54

+0

然後添加'<?php global $ detect?>'子模板的頂部...還要注意也有一個WordPress插件http://wordpress.org/extend/plugins/wp-mobile-detect/ – MonteCristo 2013-03-07 14:08:25