0

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!

Michael Giovanni Pumo
  • 14,338
  • 18
  • 91
  • 140

2 Answers2

1

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.

Mikko Saari
  • 160
  • 1
  • 9
  • I managed to solve the issue by disabling the the WP_DEBUG, but since your answer is more thorough, you get the points! Thank you :) – Michael Giovanni Pumo Jul 07 '17 at 08:26
  • Yes, disabling WP_DEBUG will remove the symptom (printing out the notice, causing the "Headers already sent" error), but not the actual problem, which is causing the notice in the first place. – Mikko Saari Jul 07 '17 at 12:01
0

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.

Michael Giovanni Pumo
  • 14,338
  • 18
  • 91
  • 140