2012-12-06 55 views
1

除了創建無限數量的模板之外,在WordPress帖子中使用JavaScript的最佳實踐是什麼?在WordPress帖子中使用JavaScript,最佳做法是什麼?

由於WordPress堅持插入pbr標籤,因此將其放置在HTML選項卡中會導致一系列問題。任何人遇到這個問題?

預先感謝您!

+0

爲什麼你需要無限量的模板?爲什麼不把JavaScript放在你的模板裏? – Brad

+2

或者只是使用插件來修復格式? http://wordpress.org/extend/plugins/allow-javascript-in-posts-and-pages/ –

回答

0

去掉空白並返回你的JS,它會工作。這不會給WP編輯器添加任何中斷和返回。

或者,在functions.php中拋出這樣的:

// <!-- noformat on --> and <!-- noformat off --> functions 

function newautop($text) 
{ 
    $newtext = ""; 
    $pos = 0; 

    $tags = array('<!-- noformat on -->', '<!-- noformat off -->'); 
    $status = 0; 

    while (!(($newpos = strpos($text, $tags[$status], $pos)) === FALSE)) 
    { 
     $sub = substr($text, $pos, $newpos-$pos); 

     if ($status) 
      $newtext .= $sub; 
     else 
      $newtext .= convert_chars(wptexturize(wpautop($sub)));  //Apply both functions (faster) 

     $pos = $newpos+strlen($tags[$status]); 

     $status = $status?0:1; 
    } 

    $sub = substr($text, $pos, strlen($text)-$pos); 

    if ($status) 
     $newtext .= $sub; 
    else 
     $newtext .= convert_chars(wptexturize(wpautop($sub)));  //Apply both functions (faster) 

    //To remove the tags 
    $newtext = str_replace($tags[0], "", $newtext); 
    $newtext = str_replace($tags[1], "", $newtext); 

    return $newtext; 
} 

function newtexturize($text) 
{ 
    return $text; 
} 

function new_convert_chars($text) 
{ 
    return $text; 
} 

remove_filter('the_content', 'wpautop'); 
add_filter('the_content', 'newautop'); 

remove_filter('the_content', 'wptexturize'); 
add_filter('the_content', 'newtexturize'); 

remove_filter('the_content', 'convert_chars'); 
add_filter('the_content', 'new_convert_chars'); 

,然後你括JS在編輯器中是這樣的:

<!-- noformat on --> 

<script type="text/javascript"> 

blah blah blah 

</script> 

<!-- noformat off --> 
0

有幾個黑客,讓你要做到這一點,但最簡單的方法是使用一個插件,將允許您將javascript添加到單個帖子。 Google拉起了this one,但我相信還有更多。

或者,您可以編寫一個「shell」JavaScript文件,該文件基於頁面的URL將<script>標記注入到標題中。假設您要將名爲testFile的腳本文件添加到名爲testPage的頁面,並且URL爲www.mydomain.com/testPage。把下面的代碼在一個名爲shell.js一個shell文件:

if (location.href === "http://www.mydomain.com/testPage") { 
     var testFile = document.createElement("script"); 
     testFile.setAttribute("src","testFile.js"); 
     document.getElementsByTagName("head")[0].appendChild(testFile); 
    } 

你需要一個單獨的腳本注入代碼片段添加到shell.js與自定義JavaScript每一頁。

然後使用WordPress內置的編輯器將<script src='shell.js'></script>添加到您的標題模板中。

WordPress還有幾個official recommendations

相關問題