我需要在站點頁腳中添加一個腳本。 我只是引用footer.php:Wordpress在頁腳中添加javascript
<script src="wp-content/file/script.js"></ script>
在家工作正常,但是當訪問一個頁面的孩子,他沒有找到,因爲搜索的目錄:
site/page-child/wp-content/file/script.js
。
我看到了,我必須使用:
wp_enqueue_script()
但我應該在哪裏把這個代碼?
感謝的
我需要在站點頁腳中添加一個腳本。 我只是引用footer.php:Wordpress在頁腳中添加javascript
<script src="wp-content/file/script.js"></ script>
在家工作正常,但是當訪問一個頁面的孩子,他沒有找到,因爲搜索的目錄:
site/page-child/wp-content/file/script.js
。
我看到了,我必須使用:
wp_enqueue_script()
但我應該在哪裏把這個代碼?
感謝的
因爲你似乎使用WordPress,你可以替換
<script src="wp-content/file/script.js"></ script>
有:
<script src="<?php site_url('/wp-content/file/script.js'); ?>"></script>
你只需要添加一個 「/」 爲了您的網址前從根啓動它:
<script src="/wp-content/file/script.js"></ script>
確實在主頁上它尋找yoursite.com/wp-content,但在其他頁面上它搜索yoursite.com/current-page/wp-content,顯然它在404結果。
添加/使它總是看對於yoursite.com/wp-content
通過這種方式,它訪問本地主機,而不是localhost/project – Daniel
@Daniel的確,但我想讓他明白爲什麼它不起作用,那麼它只是適應。考慮到他使用wordpress,更好的答案是使用wordpress自定義url –
添加<script src="wp-content/file/script.js"></ script>
不是一個乾淨的方式來加載您的JS文件,因爲這不是一個相對的URL,當您激活您的子主題可能您的主題不會加載您的JS文件,解決方案是:
<script src="<?php echo get_stylesheet_directory_uri(); ?>/js/script.js"></script>
您需要這在你的主題直銷添加到您的footer.php
文件保守黨wp-content\themes\your_theme\footer.php
但最好的方法是使用WP掛鉤,包括腳本,首先你需要使用註冊它們
wp_register_script('my_script_name', get_template_directory_uri(). '/js/script.js');
然後只需加載它們
wp_enqueue_script('my_script_name');
不要試圖註冊並將腳本直接排入footer.php文件,而是在您的functions.php
模板文件中創建一個方法,然後使用
注意:要將腳本排入頁腳,需要將$in_footer
參數設置爲true。
結帳wp_enqueue_script欲瞭解更多信息。
在哪個文件中我註冊了 'wp_register_script'? 如何將我的js電腦文件上傳到wordpress? – Daniel
將您的JS文件複製到您的主題項目中:'wp-content \ themes \ your_theme \ js'然後轉到'wp-content \ themes \ your_theme \ footer.php'並添加: '' 如果文件不存在,使用'wp_register_script'將它添加到'wp-content \ themes \ your_theme \ functions.php'創建它,它會自動加載.. –
這裏是一個如何使用這個例子: 'function load_my_script(){ wp_register_script('my_script_name',get_template_directory_uri()。'/js/script.js'); wp_enqueue_script('my_script_name'); } add_action('wp_enqueue_scripts','my_scripts_method');' –
它沒有工作 – Daniel
請您檢查執行此更改後產生的源代碼並報告此塊的輸出是什麼? –