簡體   English   中英

在 Wordpress 中使用 wp_enqueue

[英]Using wp_enqueue in Wordpress

我求助於這個很棒的社區,經過幾天的嘗試修復這個錯誤,我的問題真的很簡單,但它已經到了我身上。 我正在嘗試在使用進化主題時將 Java 腳本排隊到我的主題我的登錄插件中。

這是執行此操作的代碼片段,我使用全局函數來檢查該函數是否正在加載,並且沒有被加載。 'a' 不會變為真。

出於某種原因,它看起來像 'wp_enqueue_scripts 不起作用。 我也嘗試添加 wp_head() ,但沒有運氣。

 <?php $GLOBALS['a'] = 'false'; add_action( 'wp_enqueue_scripts', 'load_location' ); function load_location() { $GLOBALS['a'] = 'true'; wp_register_script('load_location_test',get_template_directory_uri().'/load_location.js', array('jquery'),'1.1',true); wp_enqueue_script('load_location_test'); } ?> <?php echo $GLOBALS['a'] ?>;

謝謝指教

鏈接是http://www.meetntrain.com/register

您應該查看文檔或其他插件的文件、在線演練等,以了解更多信息。 wp_enqueue_scripts是你用來加載你的 Javascript 的鈎子,你有基本的正確想法,但是在你的 functions.php 中嘗試一些更像這樣的東西:

function my_custom_scripts() {
    wp_register_script( 'custom-js', 'js/custom.js' );
    wp_enqueue_script( 'custom-js', 'js/custom.js', false );
}

add_action( 'wp_enqueue_scripts', 'my_custom_scripts' );

為您的 JS 文件所在的目錄更改“js/custom.js”。

另一種選擇,如果這被證明太難了,那就是在你的footer.php 的底部放置一個指向JS 文件的直接鏈接。 <script src="/path/to/my/file.js"></script>

不過,我確實發現排隊腳本有時有點奇怪,希望這可以幫助您弄清楚。

因此,為了讓您的入隊工作,您需要在您的functions.php文件或插件中添加代碼。

add_action( 'wp_enqueue_scripts', 'load_location' );

function load_location() {
    wp_register_script('load_location_test',get_template_directory_uri().'/load_location.js', array('jquery'),'1.1',true);
    wp_enqueue_script('load_location_test');
}

這會將 JS 文件添加到您的所有頁面。 如果要定位特定頁面,可以通過 JavaScript 或直接在 PHP 文件中進行。

如果您的主題使用body_class() ,您可以按類定位該特定頁面。 然后你應該像這樣包裝你的JS:

if( $('body.classUsed').length ){
// Your JS code here
}

請注意,該文件仍將一直排隊。 或者,如果您只想將 JS 文件添加到指定頁面,則可以將其包裝在is_page()條件中:

add_action( 'wp_enqueue_scripts', 'load_location' );

function load_location() {
    if( is_page('your-page') ){
       wp_register_script('load_location_test',get_template_directory_uri().'/load_location.js', array('jquery'),'1.1',true);
       wp_enqueue_script('load_location_test');
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM