使用AJAX调用wordpress短代码
我想使用开关按钮运行短代码。如果开关处于“开”状态,我称之为短码,如果它处于“关”状态,则打给另一个短码。使用AJAX调用wordpress短代码
作为测试我打过电话,在与AJAX一个单一链路上点击一个短代码,它给了我这样的:
文件“页面recherche.php”:
<a href="" id="clicklien">CLICK HERE</a>
<script>
$("#clicklien").click(function(e){
e.preventDefault();
$.ajax({
url: 'http://www.capitainebar.com/wp-content/themes/Capitaine-Bar/shortcode-recherche.php',
success: function (data) {
// this is executed when ajax call finished well
console.log('content of the executed page: ' + data);
$('body').append(data);
},
error: function (xhr, status, error) {
// executed if something went wrong during call
if (xhr.status > 0) alert('got error: ' + status); // status 0 - when load is interrupted
}
});
});
</script
文件名为是“shortcode-recherche.php”:
<?php echo do_shortcode('[search-form id="1" showall="1"]'); ?>
结果是致命错误。就好像代码运行在“shortcode-recherche.php”而不是“page-recherche.php”中。
请注意,如果我不通过AJAX调用将短代码直接写入我的页面,短代码工作正常。
你可以看到the result here
当你调用一个PHP文件直接,WordPress的不参与。这意味着像do_shortcode()
这样的函数甚至不存在。
相反,您需要请求一个被WordPress捕获的文件(即使通常是404)。然后,让你的插件知道URL。你可以用查询变量(简单)或重写规则(困难,漂亮)来做到这一点。例如:
查询变量:example.org/?custom_shortcode=gallery
Rerwrite规则:example.org/custom_shortcode/gallery/
无论您选择的选项,你的插件需要,当你访问这个URL并拦截其了解。完成后,您需要退出脚本以防止WordPress尝试显示404页面。
这里是一个例子,你可以简单地将它放入你的functions.php文件。
function shortcode_test() {
if (!empty($_REQUEST['shortcode'])) {
// Try and sanitize your shortcode to prevent possible exploits. Users typically can't call shortcodes directly.
$shortcode_name = esc_attr($_REQUEST['shortcode']);
// Wrap the shortcode in tags. You might also want to add arguments here.
$full_shortcode = sprintf('[%s]', $shortcode_name);
// Perform the shortcode
echo do_shortcode($full_shortcode);
// Stop the script before WordPress tries to display a template file.
exit;
}
}
add_action('init', 'shortcode_test');
你可以通过这个访问您的网站测试这个加在URL的末尾:
?shortcode=gallery
这应该显示扩展为HTML画廊简码。一旦这个工作正常,只需将其绑定到现有的AJAX功能。
好吧,我终于明白了......谢谢很多为您的帮助! – 2014-09-27 11:02:42
使用'?shortcode = search-form',它会在/ homepages/1/d543902707/htdocs/wp-content/plugins/profi-search-filter/includes/shortcode中向我返回这个警告:非法字符串偏移量'id'。在线4上的php。 如何在您给我的网址中指定我的简码的ID? – 2014-09-27 11:33:27
你好,请你看看我的问题:http://stackoverflow.com/questions/41248786/wordpress-execute-do-shortcode-inside-ajax-function – 2016-12-21 07:16:16
你能发布你收到的错误吗? – Dez 2014-09-26 23:00:44
致命错误:调用未定义的函数do_shortcode()在/homepages/1/d543902707/htdocs/wp-content/themes/Capitaine-Bar/shortcode-recherche.php在线1 – 2014-09-26 23:38:03