在WordPress帖子中使用JavaScript,最佳做法是什么?

时间:2012-12-06 17:31:20

标签: javascript wordpress

除了创建无限数量的模板外,在WordPress帖子中使用JavaScript的最佳最佳做法是什么?

将它放在HTML标签页中会给我带来一系列问题,因为WordPress会坚持插入pbr标签。其他人遇到这个问题?

提前谢谢!

2 个答案:

答案 0 :(得分: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 -->

答案 1 :(得分:0)

有一些黑客可以让你这样做,但最简单的方法是使用一个插件,允许你添加javascript到个别帖子。 Google提升了this one,但我确信还有更多。

或者,您可以编写一个“shell”javascript文件,根据页面的URL将<script>标记注入到标题中。假设您要将名为testFile的脚本文件添加到名为testPage的网页,其网址为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

相关问题