单击 wordpress 永久链接后执行 javascript 不起作用

Executing javascript after clicking on wordpress permalink not working

我有一个插件,可以在加载 wordpress 页面时将文本 {headernav} 替换为 html。当页面首次加载时它工作正常,但是如果我导航到另一个页面,{headernav} 将显示而不是 javascript.

替换的 html 内容

我尝试过的东西。

  1. 我使用了 firebug 并发现当我点击固定链接时加载了 javscript,它会转到 post 页面。

下面是插件加载的javascript代码。

Javascript:

    jQuery(document).ready(function($){//begin document ready function call
      //place needed javascript for the plugin elements inside this function call   


     $.get("wp-content/plugins/elemental/content/headernav.php",function(element){

//the tag to replace
var headernav = "{headernav}";

//create instance of RegExp
var regEx = new RegExp(headernav,"g");

//get the html of the body
var html = $("body").html();

//replace the {headernav} with the html returned by the get method
var newValue = html.replace(regEx,element);

//update the body with the new html value
$("body").html(newValue);


});

//do not place any javascript code on or past this line
});//end document ready function call

使用wp_localize_script to pass variables into your plugin. Also do use the built in ajax functions by Wordpress. Take a look to this article

根据我的评论,您的 $.get() 路径似乎有问题,它会在 404 上产生错误并且不执行代码。

绝对路径或配置文件通常通过在路径前添加一个 / 就足够了,所以 /wp-content/plugins/elemental/content/headernav.php

这将在您的域根 (www.example.com) 启动 javascript,然后从那里构建到您想要的路径。

为了确保它仅在您的域中,我通常还会为根目录添加一个配置文件,而不是仅仅依赖于使用绝对路径。

希望对您有所帮助。