简体   繁体   中英

How to output JSON for WordPress search page using Relevanssi?

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!

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM