我想使用切换按钮运行短代码。如果开关为“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 调用,则短代码可以正常工作。
你可以看到结果在这里 http://www.capitainebar/recherche
当你直接调用PHP文件时,WordPress不参与其中。这意味着函数类似于do_shortcode()
甚至不存在。
相反,您需要请求 WordPress 捕获的文件(即使通常是 404)。然后,让您的插件识别该 URL。您可以使用查询变量(简单)或重写规则(困难,更漂亮)来完成此操作。例如:
查询变量:example.org/?custom_shortcode=gallery
重写规则: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 功能绑定即可。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)