問題描述
我需要一種方法來過濾頁面/帖子內容之前加載,所以如果一個特定的短代碼存在,我可以添加腳本到標題。經過多次搜索,我在 http://wpengineer.com 上碰到過
function has_my_shortcode($posts) {
if ( empty($posts) )
return $posts;
$found = false;
foreach ($posts as $post) {
if ( stripos($post->post_content, '[my_shortcode') )
$found = true;
break;
}
if ($found){
$urljs = get_bloginfo( 'template_directory' ).IMP_JS;
wp_register_script('my_script', $urljs.'myscript.js' );
wp_print_scripts('my_script');
}
return $posts;
}
add_action('the_posts', 'has_my_shortcode');
這是絕對輝煌,做了我所需要的。
現在我需要進一步擴展它,併為側邊欄做同樣的事情。它可以通過特定的小工具類型,短代碼,代碼片段或其他任何可以確定腳本需要加載的功能。
問題是我無法弄清楚在側邊欄加載之前如何訪問側邊欄內容 (相關主題將有幾個側邊欄)
最佳解決方案
您可以使用功能 is_active_widget 。例如。:
function check_widget() {
if( is_active_widget( '', '', 'search' ) ) { // check if search widget is used
wp_enqueue_script('my-script');
}
}
add_action( 'init', 'check_widget' );
要在僅加載小工具的頁面中加載腳本,您必須在您的小工具類中添加 is_active_widget() 代碼。例如,參見默認的最近評論小工具 (wp-includes /default-widgets.php,第 602 行):
class WP_Widget_Recent_Comments extends WP_Widget {
function WP_Widget_Recent_Comments() {
$widget_ops = array('classname' => 'widget_recent_comments', 'description' => __( 'The most recent comments' ) );
$this->WP_Widget('recent-comments', __('Recent Comments'), $widget_ops);
$this->alt_option_name = 'widget_recent_comments';
if ( is_active_widget(false, false, $this->id_base) )
add_action( 'wp_head', array(&$this, 'recent_comments_style') );
add_action( 'comment_post', array(&$this, 'flush_widget_cache') );
add_action( 'transition_comment_status', array(&$this, 'flush_widget_cache') );
}
次佳解決方案
只是想分享一個解決方案,這使我在我的實現中變得更加多樣化。而不是對各種短信進行功能檢查,我修改了它,以尋找引用需要排入隊列的腳本/樣式函數的單個短代碼。這將適用於其他類中的兩種方法 (例如可能無法自己完成的插件) 和 in-scope 功能。只需將以下代碼放在 functions.php 中,並將以下語法添加到您想要的特定 CSS& JS 。
頁面/後綴語法:[loadCSSandJS function =「(class-> method /function name)」]
functions.php 代碼:
function page_specific_CSSandJS( $posts ) {
if ( empty( $posts ) )
return $posts;
foreach ($posts as $post) {
$returnValue = preg_match_all('#[loadCSSandJS function="([A-z->]+)"]#i', $post->post_content, $types);
foreach($types[1] as $type) {
$items = explode("->",$type);
if (count($items) == 2) {
global $$items[0];
if( method_exists( $$items[0], $items[1] ))
add_action( 'wp_enqueue_scripts', array(&$$items[0], $items[1]) );
}
else if( !empty( $type ) && function_exists( $type ))
add_action( 'wp_enqueue_scripts', $type );
}
}
return $posts;
}
這也將允許您在頁面上添加所需的數量。請記住,您需要一個加載方法/函數。
參考文獻
注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。