doufei9805
2017-07-05 16:11
浏览 39

如何使用Relevanssi为WordPress搜索页面输出JSON?

I'm using the WordPress search plugin Relevanssi.

I'm trying to customise my search.php template to output JSON, like so:

<?php

header('Content-Type: application/json');

$results = array();

if (have_posts()):
  while (have_posts()): 
    the_post();
    $results[] = array(
      'permalink' => get_permalink(),
      'title' => get_the_title()
    );
  endwhile;
endif;

echo json_encode($results);

die();

?>

However, I'm getting an error that headers are already sent.

Warning: Cannot modify header information - headers already sent by (output started at /Applications/MAMP/htdocs/NBC/wp-content/plugins/relevanssi/lib/search.php:554) in /Applications/MAMP/htdocs/NBC/wp-content/themes/NBC/search.php on line 3

Is there a better way to do this? The reason I need it as JSON is that I want to consume it with JS.

I have done this before on an older site, so perhaps the issues are with the latest version I'm using? 3.5.11

Note that the query DOES return results, but I get these errors on the page too, which causes me to receive invalid JSON data back.

Thanks!

图片转代码服务由CSDN问答提供 功能建议

我正在使用WordPress搜索插件 Relevanssi

我正在尝试自定义 search.php 模板以输出JSON,如下所示:

   &lt;?php 
 
header('Content-Type:application / json'); 
 
 $ results = array(); 
 
if(have_posts()):
 while(have_posts()):  
 the_post(); 
 $ results [] = array(
'permalink'=&gt; get_permalink(),
'title'=&gt; get_the_title()
); 
 endwhile; 
endif; \  n 
echo json_encode($ results); 
 
die(); 
 
?&gt; 
   
 
 

但是,我收到标题错误 已经发送。

警告:无法修改标头信息 - 已经由 发送的标头(输出从 开始\ / Applications / MAMP /htdocs/NBC/wp-content/plugins/relevanssi/lib/search.php:554)hn在 /Applications/MAMP/htdocs/NBC/wp-content/themes/NBC/search.php on 第3行

有更好的方法吗? 我需要它作为JSON的原因是我想用JS来使用它。

我之前在一个旧网站上做过这个,所以也许问题是我最新的版本 使用? 3.5.11

请注意,查询会返回结果,但我也会在页面上收到这些错误,这会导致我收回无效的JSON数据。< / p>

谢谢!

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dongmao7195 2017-07-07 03:36
    已采纳

    Relevanssi 3.5.11 has a small bug. It doesn't affect the plugin use in any way, but with WP_DEBUG enabled, it throws a notice for an undefined variable. That's why you're seeing that "headers already sent" error.

    If you want to keep WP_DEBUG enabled, you need to fix that bug. The fix is simple: add this to lib/search.php on line 382 to define the variable.

    $non_post_post_type = NULL;

    This fix will be included in the version 3.5.12.

    点赞 打赏 评论
  • dongluo6343 2017-07-06 09:30

    The issue goes away if I turn off WP_DEBUG in wp-config.php

    define('WP_DEBUG', false);
    

    It must be something to do with WordPress internals that I don't understand.

    点赞 打赏 评论

相关推荐 更多相似问题