1
我在這裏發現了這個偉大的教程:codropsWordPress的縮略圖電網擴大預覽
,但我無法弄清楚如何讓它在WordPress的工作!我是一個初學者/中級使用Javascript,但我真的不知道如何將其插入Wordpress。 Wordpress Codex提到將腳本直接放入帖子中,因爲它不會在站點範圍內使用。有沒有人成功地得到這個工作?你能給我說明如何做到這一點嗎?
我在這裏發現了這個偉大的教程:codropsWordPress的縮略圖電網擴大預覽
,但我無法弄清楚如何讓它在WordPress的工作!我是一個初學者/中級使用Javascript,但我真的不知道如何將其插入Wordpress。 Wordpress Codex提到將腳本直接放入帖子中,因爲它不會在站點範圍內使用。有沒有人成功地得到這個工作?你能給我說明如何做到這一點嗎?
這裏是你可以做到這一點的方法之一。通過在你的functions.php文件中創建一個短代碼,你可以包含你需要的js資源。請注意,對於此實現,您必須在本地包含此行中定義的資源:element.src = '/wp-content/themes/custom_name_space/js/$src';
或者您可以使用某種插件讓您將自定義j添加到帖子中。
/** you will need to include this invocation in the source file. */
$(function() {
Grid.init();
});
<?php add_shortcode('custom_name_space_addJs', function ($atts) {
/**
* create a javascript shortcode
* shortcode takes an id attribute and src attribute
* leaving src attribute blank will generate a 404 Error Code
*/
extract(shortcode_atts(array(
'id'=>'js-custom_name_space-script', 'src' => 'no-script.js',), $atts)); return "
<script id='js-add-script-element'>
(function(w, doc) {
'use strict';
function downloadJSAtOnload() {
var element = doc.createElement('script');
element.id = '$id';
element.src = '/wp-content/themes/custom_name_space/js/$src';
doc.body.appendChild(element);
}
/* Check for browser support of event handling capability */
if (w.addEventListener) {
w.addEventListener('load', downloadJSAtOnload, false);
} else if (w.attachEvent) {
w.attachEvent('onload', downloadJSAtOnload);
} else {
w.onload = downloadJSAtOnload;
}
}(window, document));
</script>"; }); ?>
<!-- Then inside a wordpress post, write the needed HTML from the tutorial and use the short code -->
[custom_name_space_addJs id="thumb-grid" src="grid.js"]
感謝您的答覆!但我認爲我做了一些錯誤的事情。我得到了死亡的白色屏幕,然後我註釋了我在functions.php文件中插入的代碼,現在網站又重新啓動了。我有幾個短後續問題:
- 請問你給調用代碼放置在grid.js文件還需要放在modernizr.custom.js也文件?
- id和src屬性讓我困惑了一下。它是否與我爲id選擇的名稱有關係?對於src我想象它與element.src相同?
– Jarrel09$(function() { custom.modernizr.init(); });
確保開啓和關閉php標籤位於您的文件的適當位置。不,該代碼只需要放在grid.js的末尾。 id屬性是任意的,但它應該是唯一的並且對調試很有幫助,因此您可以輕鬆找到腳本標籤。而src屬性只是文件名,因爲我已經指向主題中的一個路徑,然後文件名被連接起來。 – colecmc