【问题标题】:Call wordpress shortcode with AJAX使用 AJAX 调用 wordpress 简码
【发布时间】:2014-11-22 01:01:58
【问题描述】:

我想使用切换按钮运行简码。如果开关是“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

【问题讨论】:

  • 你能发布你收到的错误吗?
  • 致命错误:在第 1 行调用 /homepages/1/d543902707/htdocs/wp-content/themes/Capitaine-Bar/shortcode-recherche.php 中未定义的函数 do_shortcode()

标签: php jquery ajax wordpress shortcode


【解决方案1】:

直接调用 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 函数绑定即可。

【讨论】:

  • 好的,我终于明白了...非常感谢您的帮助!
  • 使用?shortcode=search-form,它会返回给我这个Warning: Illegal string offset 'id' in /homepages/1/d543902707/htdocs/wp-content/plugins/profi-search-filter/includes/shortcode.php on line 4。如何在您给我的 URL 中指定我的短代码的 ID?
猜你喜欢
  • 2012-11-10
  • 1970-01-01
  • 2019-07-13
  • 1970-01-01
  • 2016-07-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多