我想使用切换按钮来运行简码。如果开关为“ 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调用直接将其写到页面中,则该短代码可以正常工作。
当您直接调用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函数即可。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句