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.