2015-04-26 68 views
1

我正在使用下面的方法在WordPress管理中使用jQuery庫,這工作正常,我不需要爲此方法添加jQuery庫的源代碼。如何將WordPress jQuery庫添加到前端

<script> 
     jQuery(document).ready(function(){ 
      // works inside WordPress admin without source 
     }); 
    </script> 

但是,同樣的方法不適用於前端WordPress窗體,並使其工作我要添加庫的源?

<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> 
<script> 
     jQuery(document).ready(function(){ 
      // need to add jQuery source 
     }); 
    </script> 

爲什麼我需要爲前端添加jQuery庫的源代碼?如何將WordPress JQuery庫加載到前端?

回答

1

它在管理員工作,因爲有管理腳本有jQuery作爲依賴和WordPress包括jQuery爲了這些腳本工作。

添加腳本(不包括它們在腳本標記中)時,應該使用wp_enqueue_script()函數。注意該函數的變量$deps,如果將其設置爲array('jquery'),WordPress將爲您包含該庫,以便您的腳本可以使用它。

If you scroll down the page您可以看到哪些庫包含在WordPress中,以及使用哪些句柄對它們進行排隊。

0

您首先需要確保jQuery已入隊。它應該只是以確保它是添加下面的header.php中

<?php 
function my_jq_queue() { 
    wp_enqueue_script('jquery'); 
} 

add_action('wp_enqueue_scripts', 'my_jq_queue'); 
?> 

後,您可以添加腳本如下

<script type="text/javascript"> 
jQuery(document).ready(function($) { 
     // add add your function in the format $() 

    }); 
</script> 
+0

我已經在插件添加此。我需要將其添加到插件?是添加在主插件文件中? –

+0

php函數應該作爲主插件文件中的單獨函數運行。你可以添加JavaScript內聯或也與鏈接到JavaScript文件排隊它看到鏈接[http://code.tutsplus.com/articles/the-ins-and-outs-of-the-enqueue-script-for -wordpress主題-和插件 - WP-22509(http://code.tutsplus.com/articles/the-ins-and-outs-of-the-enqueue-script-for-wordpress-themes-and -plugins - wp-22509) –

+0

請檢查我的這個問題http://stackoverflow.com/questions/29983563/add-wordpress-jquery-to-cutom-page-template –