我想使用开关按钮运行短代码。如果开关是“ON”,我会拨打一个短代码,如果是“OFF”,我会拨打另一个短信。
作为一项测试,我尝试使用AJAX点击一个链接时调用一个短代码,它给了我这个:
文件“page-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
答案 0 :(得分:2)
直接调用PHP文件时,不涉及WordPress。这意味着像do_shortcode()
这样的函数甚至不存在。
相反,您需要请求一个由WordPress捕获的文件(即使通常是404)。然后,让您的插件知道URL。您可以使用查询变量(简单)或重写规则(困难,更漂亮)来执行此操作。例如:
查询变量:example.org/?custom_shortcode=gallery
Rerwrite rule:example.org/custom_shortcode/gallery/
无论您选择哪个选项,当您访问此网址并拦截它时,您的插件都需要注意。完成后,您需要退出脚本以防止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');
您可以通过访问您的网站来测试这一点,并在网址末尾添加:
?shortcode=gallery
这应该显示扩展为HTML的图库短代码。一旦这个工作,只需将它绑定到您现有的AJAX函数。