How to output JSON for WordPress search page using Relevanssi? - php

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.

Related

Expression engine showing garbage content while using PHP

Expressionengine is showing garbage value when I am using php for Json encode its showing this content {!-- ra:0000000019930c5000007efd6bf7e0f5 --}
here is my code :-
<?php
$entries = array();
{exp:channel:entries channel="sport" category="3536|1830|4102" site="default_site" limit="3" track_views="one" dynamic="no" status="open|featured" disable="categories|category_fields|pagination|member_data" terminate="yes"}
$entries[] = array('title' => '{title}');
{/exp:channel:entries}
header('Content-type: application/json');
echo json_encode($entries);
exit;
?>
If you see this kind of garbage value on the page that means the page has an error.
We mostly find this garbage value on PHP-enabled templates. So if we resolve the PHP errors the garbage will go.
Do not modify the ExpressionEngine core files. If you want to see the PHP errors on the page, turn on the debug mode.
If you remove the exit() function, you will get the output as you want.
The exit() function also exits the execution of ExpressionEngine code that's why you are getting the garbage value.
Even simpler - remove the exit().
As this answer explains, these are annotation tags used for debugging (so you can get a stack trace for nested templates I suppose) and they are parsed out late in the process. So if you exit() it doesn't work. Just make sure that the script ends with no unwanted output and you should be good. I had this problem (in EEv5) and this was the fix.
I've just had the same style of error codes appear, when moving an old EE 2.9.3 site to a Dev server and applying a test domain name.
There were some PHP Includes in the templates, which referenced the live site's server path. When I changed these... all fixed.
For example:
include("/home/sites/domainname.co.uk/public_html/swift/swift_required.php");
...changed to...
include("/home/domain/public_html/swift/swift_required.php");
Yeah ! finally I got the answer its so simple here is the solution :-
go to ExpressionEngine\system\EllisLab\ExpressionEngine\Library\Template\Annotation\Runtime.php
on line no. 65 comment the code return '{!-- ra:'.$key.' --}';

WordPress having trouble working outside of itself

I'm trying to call WordPress functions on an external page. I've been able to get rid of the first hurdle which had the error of:
This Plugin Requires WordPress 3.1+ or Greater: Activation Stopped!
By literally disabling everything on my site.
Now I am facing another little issue.
I've added this requirement statement: <?php require('/path/to/my/wp-blog-header.php'); ?>
And I get the following error. Of course this requirement statement is outside of any class.
Fatal error: Call to a member function main() on a non-object in /home2/phanime/public_html/wp-includes/functions.php on line 781
I've also looked around before asking, and people said to add the following line: global $wpdb; and it didn't help, the error still persists.
I've also tried simply putting that line of code (the required statement) and the issue still persists.
As suggested by someone, I'll update this question. I've got the initialization working but now I am not able to use WP_Query or get_posts and they don't return anything. For example this code I tried
$testingQuery = get_posts(array(
'post_type' => 'anime',
'order' => 'date'
));
Then with an if / else statement I check if the variable is empty or not
if ($testingQuery) {
foreach( $testingQuery as $post ) : setup_postdata($post);
$contents .= '<li id="ourTab" class="profileContent">
<div class="section">AnimeList Coming soon.</div>
</li>';
$contents .= get_the_title();
endforeach;
} else {
$contents .= '<li id="ourTab" class="profileContent">
<div class="section">Test</div>
</li>';
}
In this case the else statement runs which tells me that the variable is empty or what not, as "Test" is displayed.
Furthermore, I remove the if / else statement and just try the foreach loop to see the exact error I get.
And this is the error
Invalid argument supplied for foreach() in /home2/asdf/public_html/community/library/asdfTab/Listener.php, line 54:
I've also tried the same thing with WP_Query and the variables are returning empty so I don't know what the exact problem is, but it seems that they are not able to retrieve the posts that I am requesting.
you need to initialize WordPress before calling any functions.
Try requiring wp-config.php into your external page before calling any functions.
put the following in the beginning of your external script
<?php
require_once("path/to/wp-load.php");
then wp will bootstrap and you can call additional functions
Looks like you need to reinstall Wordpress. BACKUP YOUR STUFF BEFORE DOING IT.

WordPress plugin activation error: unexpected output during activation [duplicate]

I'm getting this message each time I activate my plugin:
The plugin generated 80 characters of unexpected output during activation. If you notice “headers already sent” messages, problems with syndication feeds or other issues, try deactivating or removing this plugin.
The only way I was able to suppress the message was to wrap my activation function code within an if statement (please refer to snippets below).
Here, a snippet of my plugin code when I get the error described above:
function myPlugin( $post ) {
echo "Whatever is here throws an unexpected output alert when the plugin isa activated";
}
register_activation_hook( __FILE__, 'myPlugin' );
Following, my wrapping the function in my plugin within an if statement; it suppresses the previous error as discussed above:
function myPlugin( $post ) {
global $pagenow;
if ( is_admin() && $pagenow !== 'plugins.php' ) {
echo "No more alerts when its wrapped this way";
}
}
}
register_activation_hook( __FILE__, 'myPlugin' );
What actually cause that error and how can I effectively complete my plugin with my logics without having to encounter it?
Is there any better way to handle this?
2 probably reasons:
1) You are doing an output (like echo or etc) in wrong place.
Do you want to output a message in admin dashboard? - use admin_notices hook and output there...
Do you want to output a message in front-end? - find appropriate places with hooks (like the_content or wp_footer or whatever).
Don't output anything either in register_activation_hook or outside of WordPress standard hooks, no-one should do that.**
2) if you aren't doing any output intentionally, then maybe some php error happens? If so, put this code temporarily in functions.php and then activate the plugin - you will see the error.
define('temp_file', ABSPATH.'/_temp_out.txt' );
add_action("activated_plugin", "activation_handler1");
function activation_handler1(){
$cont = ob_get_contents();
if(!empty($cont)) file_put_contents(temp_file, $cont );
}
add_action( "pre_current_active_plugins", "pre_output1" );
function pre_output1($action){
if(is_admin() && file_exists(temp_file))
{
$cont= file_get_contents(temp_file);
if(!empty($cont))
{
echo '<div class="error"> Error Message:' . $cont . '</div>';
#unlink(temp_file);
}
}
}
Had the same error, but only with 6 characters )
so... in my case I had empty lines after PHP closing tag ?> - that will cause this error too.
I think there may be two issues here that are causing the problem. First is that I don't think wordpress expects any output when the plugin activation hook is called so it may be complaining about that. Second is that plugin activation hooks are called fairly early in the wordpress program flow, so, it's probably being called before headers are sent. If ANY output is generated before calling header() then PHP usually complains.
Usually the plugin activation routine is reserved for basic setup of the plugin, calls to things like set_option() and the like.
I had the same error - 3 characters of unexpected output and was lead here. For people in my scenario another cause of this message can be the file type being encoded as UTF with BOM.
BOM encoding was causing the error, and while the plug-in activated it would render incorrectly in internet explorer because of this.
The solution is to use Notepad++ and choose 'Convert to UTF without BOM', or if you are using visual studio, there is an explanation of how to change encoding UTF-8 without BOM
I battled this problem for a long time. Typically this is caused by spaces or new lines before the opening <?php tag or after the closing ?> tag. Once I removed these, the error went away.
Also, never assume anything about GET, POST, COOKIE and REQUEST variables. Always check first using isset() or empty().
In my case it was due to Undefined index, Just enable the debug log to check whats causing it, then you can resolve it easily.
For those who don't know how to enable the Debug log, Add these lines in your wp-config.php:
define( 'WP_DEBUG', true );
define( 'WP_DEBUG_DISPLAY', true );
define( 'WP_DEBUG_LOG', true );
You can see the errors properly in the debug file created in wp-content
sometime it is because you use <?php ;?> unnecessary or use it like shown below
;?>
<?php
this extra line between closing and starting tag may also cause this error, simple remove that line/space
A common way to assign the register_activation_hook is using a static method of a class. This ensures that your plugin activation function name won't collide with other plugins.
class Foo_Plugin
{
public static function plugin_activation() {
// activation logic
}
}
This function needs to be public and not private. A mistake is easily made though, so this could be a reason for your problems when getting this kind of error.
You would then register the activation with this code in the main plugin file.
register_activation_hook( __FILE__, array( 'Foo_Plugin', 'plugin_activation' ) );
The error message The plugin generated *X* characters of unexpected output during activation is not very helpful or at least not quite enough.
To help locate the issue, add these to wp-config.php:
define( 'WP_DEBUG', true );
define( 'WP_DEBUG_LOG', true );
Then check wp-content/debug.log for more detailed error messages as to the origin of the error.
I had the same problem. I noticed that there were new lines at the beginning of the file. So I removed them and the errors disappeared. Try removing the new lines at the beginning of your files. That may help.
For beginner level developer its must be empty line break after "?>" closing of php tags.
Try removing all empty line break after this.
This problem can be solved by removing extra whitespaces. I solved this problem for my code. You can remove extra whitespaces easily in Adove Dreamweaver.
First, goto edit->Find and Replace. Or press Ctrl+F. Check "Use Regular Expression" button from "option" section.
Fill "find" field with the below code
[\r\n]{2,}
Fill "Replace" field with the below code
\n
Now click on "Replace All" button.
Hope It will work.
I was having the same issue, i tried to remove the code and did everything but still the same problem
the real solution for me was the following.
at the end of the file which contains the header of the plugin i removed closing php ?> and the problem will be solved
at the end of the plugin file which contains the header of the plugin remove the extra line breaks after the closing php ?>
my plugin file ended at line 69 and there were 7 more spaced after the last php code so in the editor the file was up to 66, my error was "The plugin generated 7 characters of unexpected...." when i removed extra lines up to 69 the was error gone,
Thanks
First sight checklist for unexpected output error on plugin.
Remove closing php tag ?> in all php file of plugin.
Remove empty space before php tag <?php
Avoid echo content in function/hook otherwise clean buffer when needed.
check here to see more info you can use:
<?php
include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
If (is_plugin_active('wshops/init.php'))
{
//Run your plugin includes files or functions
}
in your init php file.
i also got this problem when i activate my plugin
The plugin generated 1 characters of unexpected output during activation. If you notice “headers already sent” messages, problems with syndication feeds or other issues, try deactivating or removing this plugin.
Typically this is caused by spaces or new lines before the opening tag. Once I removed these, the error went away.
now my plugin error gone.
My problem was that in the main php file, i had appended at the end of the file a javascript function. It seems that wordpress hooks such of a function in the head element. I externalised that function into a java script file.
Before:
<?php
/**
* Plugin Name: yyy
* Description: yyy
* Author: yyy
* Author URI: yyy
* Version: yyy
*/
/* many functions here */
function insert_in_header() {
echo '<script type="text/javascript">',
"perform_redirection(", '"', get_option('root'), '"', ", ", '"', get_option('redirect_to'), '");',
'</script>';
}
add_action('wp_head', 'insert_in_header');
?>
<--! PROBLEMS HERE-->
<script type = "text/javascript">
function perform_redirections(root, redirectionLink) {
// code here
}
</script>
After:
<?php
/**
* Plugin Name: yyy
* Description: yyy
* Author: yyy
* Author URI: yyy
* Version: yyy
*/
/* many functions here */
function insert_in_header() {
// in headscripts.js i put the perform_redirection function
echo '<script type="text/javascript" src="', plugins_url('js/headscripts.js', __FILE__ ), '"> </script>';
echo '<script type="text/javascript">',
"perform_redirection(", '"', get_option('root'), '"', ", ", '"', get_option('redirect_to'), '");',
'</script>';
}
add_action('wp_head', 'insert_in_header');
?>
For me there was some kind of error which was being swallowed and not caught during debug
If ound this article here which explains how to determin what this output actually is
$unexpectedOutput= ob_get_contents();
now you have it, you can echo it or inspect it during debug to find out what the hells going wrong, for me it was a prolem with a database script.
Credit to the article below
https://www.toddlahman.com/the-plugin-generated-x-characters-of-unexpected-output-during-activation/
just make the function static which your are calling on activation hook
Opening the PHP file in Notepad and saving it with ANSI encoding did the trick for me. It did not cause the issue to happen again even when I opened and saved it later in Visual Studio Code.
Thanks to Todd
After trying every answer and still coming short, I figured out my issue which was different to all answers here.
Basically, the unexpected characters were coming from my error log on the MAMP server. The errors weren't displaying on frontend or Wordpress installation error log, even with WP_DEBUG, WP_DEBUG_DISPLAY and display_errors = On in the php.ini
I eventually knew it was an error causing the umm error, so I dug a bit deeper and found some errors in my php_error.log which is located in MAMP/logs/php/php_error.log
Fixed the errors and the message from wordpress went away on activation.
I had the same problem and I just changed the private function to static and it's solved.
private function db_setup() { ....
to
static function db_setup() { ....
I hope this be helpful...
In my case I had added extra blank space before start <?php tag, what a wired error though
In my case, i forget to delete var_dump inside my __construct(). I just delete it and the warn not appear anymore.
I had this same issue. In my case, I was creating some tables when this error occurred. After further digging, I realized that I had this error happening when activating my plugin which then creates the tables.
Error Code: 1060. Duplicate column name 'stadium_id'
A simple mistake as you can see. However, because it threw an error, it caused the same header output error (“headers already sent” messages, problems with syndication feeds or other issues, try deactivating or removing this plugin.) to display on the plugin page after activating.
Final thoughts, ensure that your code is not triggering any errors as this will and can cause the issue! Also, do not echo a message when using the register_activation_hook as already mentioned by T.Todua. Instead, use the admin_notices hook. https://developer.wordpress.org/reference/hooks/admin_notices/

Why this Error occured while installing wordpress plugin? [duplicate]

I'm getting this message each time I activate my plugin:
The plugin generated 80 characters of unexpected output during activation. If you notice “headers already sent” messages, problems with syndication feeds or other issues, try deactivating or removing this plugin.
The only way I was able to suppress the message was to wrap my activation function code within an if statement (please refer to snippets below).
Here, a snippet of my plugin code when I get the error described above:
function myPlugin( $post ) {
echo "Whatever is here throws an unexpected output alert when the plugin isa activated";
}
register_activation_hook( __FILE__, 'myPlugin' );
Following, my wrapping the function in my plugin within an if statement; it suppresses the previous error as discussed above:
function myPlugin( $post ) {
global $pagenow;
if ( is_admin() && $pagenow !== 'plugins.php' ) {
echo "No more alerts when its wrapped this way";
}
}
}
register_activation_hook( __FILE__, 'myPlugin' );
What actually cause that error and how can I effectively complete my plugin with my logics without having to encounter it?
Is there any better way to handle this?
2 probably reasons:
1) You are doing an output (like echo or etc) in wrong place.
Do you want to output a message in admin dashboard? - use admin_notices hook and output there...
Do you want to output a message in front-end? - find appropriate places with hooks (like the_content or wp_footer or whatever).
Don't output anything either in register_activation_hook or outside of WordPress standard hooks, no-one should do that.**
2) if you aren't doing any output intentionally, then maybe some php error happens? If so, put this code temporarily in functions.php and then activate the plugin - you will see the error.
define('temp_file', ABSPATH.'/_temp_out.txt' );
add_action("activated_plugin", "activation_handler1");
function activation_handler1(){
$cont = ob_get_contents();
if(!empty($cont)) file_put_contents(temp_file, $cont );
}
add_action( "pre_current_active_plugins", "pre_output1" );
function pre_output1($action){
if(is_admin() && file_exists(temp_file))
{
$cont= file_get_contents(temp_file);
if(!empty($cont))
{
echo '<div class="error"> Error Message:' . $cont . '</div>';
#unlink(temp_file);
}
}
}
Had the same error, but only with 6 characters )
so... in my case I had empty lines after PHP closing tag ?> - that will cause this error too.
I think there may be two issues here that are causing the problem. First is that I don't think wordpress expects any output when the plugin activation hook is called so it may be complaining about that. Second is that plugin activation hooks are called fairly early in the wordpress program flow, so, it's probably being called before headers are sent. If ANY output is generated before calling header() then PHP usually complains.
Usually the plugin activation routine is reserved for basic setup of the plugin, calls to things like set_option() and the like.
I had the same error - 3 characters of unexpected output and was lead here. For people in my scenario another cause of this message can be the file type being encoded as UTF with BOM.
BOM encoding was causing the error, and while the plug-in activated it would render incorrectly in internet explorer because of this.
The solution is to use Notepad++ and choose 'Convert to UTF without BOM', or if you are using visual studio, there is an explanation of how to change encoding UTF-8 without BOM
I battled this problem for a long time. Typically this is caused by spaces or new lines before the opening <?php tag or after the closing ?> tag. Once I removed these, the error went away.
Also, never assume anything about GET, POST, COOKIE and REQUEST variables. Always check first using isset() or empty().
In my case it was due to Undefined index, Just enable the debug log to check whats causing it, then you can resolve it easily.
For those who don't know how to enable the Debug log, Add these lines in your wp-config.php:
define( 'WP_DEBUG', true );
define( 'WP_DEBUG_DISPLAY', true );
define( 'WP_DEBUG_LOG', true );
You can see the errors properly in the debug file created in wp-content
sometime it is because you use <?php ;?> unnecessary or use it like shown below
;?>
<?php
this extra line between closing and starting tag may also cause this error, simple remove that line/space
A common way to assign the register_activation_hook is using a static method of a class. This ensures that your plugin activation function name won't collide with other plugins.
class Foo_Plugin
{
public static function plugin_activation() {
// activation logic
}
}
This function needs to be public and not private. A mistake is easily made though, so this could be a reason for your problems when getting this kind of error.
You would then register the activation with this code in the main plugin file.
register_activation_hook( __FILE__, array( 'Foo_Plugin', 'plugin_activation' ) );
The error message The plugin generated *X* characters of unexpected output during activation is not very helpful or at least not quite enough.
To help locate the issue, add these to wp-config.php:
define( 'WP_DEBUG', true );
define( 'WP_DEBUG_LOG', true );
Then check wp-content/debug.log for more detailed error messages as to the origin of the error.
I had the same problem. I noticed that there were new lines at the beginning of the file. So I removed them and the errors disappeared. Try removing the new lines at the beginning of your files. That may help.
For beginner level developer its must be empty line break after "?>" closing of php tags.
Try removing all empty line break after this.
This problem can be solved by removing extra whitespaces. I solved this problem for my code. You can remove extra whitespaces easily in Adove Dreamweaver.
First, goto edit->Find and Replace. Or press Ctrl+F. Check "Use Regular Expression" button from "option" section.
Fill "find" field with the below code
[\r\n]{2,}
Fill "Replace" field with the below code
\n
Now click on "Replace All" button.
Hope It will work.
I was having the same issue, i tried to remove the code and did everything but still the same problem
the real solution for me was the following.
at the end of the file which contains the header of the plugin i removed closing php ?> and the problem will be solved
at the end of the plugin file which contains the header of the plugin remove the extra line breaks after the closing php ?>
my plugin file ended at line 69 and there were 7 more spaced after the last php code so in the editor the file was up to 66, my error was "The plugin generated 7 characters of unexpected...." when i removed extra lines up to 69 the was error gone,
Thanks
First sight checklist for unexpected output error on plugin.
Remove closing php tag ?> in all php file of plugin.
Remove empty space before php tag <?php
Avoid echo content in function/hook otherwise clean buffer when needed.
check here to see more info you can use:
<?php
include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
If (is_plugin_active('wshops/init.php'))
{
//Run your plugin includes files or functions
}
in your init php file.
i also got this problem when i activate my plugin
The plugin generated 1 characters of unexpected output during activation. If you notice “headers already sent” messages, problems with syndication feeds or other issues, try deactivating or removing this plugin.
Typically this is caused by spaces or new lines before the opening tag. Once I removed these, the error went away.
now my plugin error gone.
My problem was that in the main php file, i had appended at the end of the file a javascript function. It seems that wordpress hooks such of a function in the head element. I externalised that function into a java script file.
Before:
<?php
/**
* Plugin Name: yyy
* Description: yyy
* Author: yyy
* Author URI: yyy
* Version: yyy
*/
/* many functions here */
function insert_in_header() {
echo '<script type="text/javascript">',
"perform_redirection(", '"', get_option('root'), '"', ", ", '"', get_option('redirect_to'), '");',
'</script>';
}
add_action('wp_head', 'insert_in_header');
?>
<--! PROBLEMS HERE-->
<script type = "text/javascript">
function perform_redirections(root, redirectionLink) {
// code here
}
</script>
After:
<?php
/**
* Plugin Name: yyy
* Description: yyy
* Author: yyy
* Author URI: yyy
* Version: yyy
*/
/* many functions here */
function insert_in_header() {
// in headscripts.js i put the perform_redirection function
echo '<script type="text/javascript" src="', plugins_url('js/headscripts.js', __FILE__ ), '"> </script>';
echo '<script type="text/javascript">',
"perform_redirection(", '"', get_option('root'), '"', ", ", '"', get_option('redirect_to'), '");',
'</script>';
}
add_action('wp_head', 'insert_in_header');
?>
For me there was some kind of error which was being swallowed and not caught during debug
If ound this article here which explains how to determin what this output actually is
$unexpectedOutput= ob_get_contents();
now you have it, you can echo it or inspect it during debug to find out what the hells going wrong, for me it was a prolem with a database script.
Credit to the article below
https://www.toddlahman.com/the-plugin-generated-x-characters-of-unexpected-output-during-activation/
just make the function static which your are calling on activation hook
Opening the PHP file in Notepad and saving it with ANSI encoding did the trick for me. It did not cause the issue to happen again even when I opened and saved it later in Visual Studio Code.
Thanks to Todd
After trying every answer and still coming short, I figured out my issue which was different to all answers here.
Basically, the unexpected characters were coming from my error log on the MAMP server. The errors weren't displaying on frontend or Wordpress installation error log, even with WP_DEBUG, WP_DEBUG_DISPLAY and display_errors = On in the php.ini
I eventually knew it was an error causing the umm error, so I dug a bit deeper and found some errors in my php_error.log which is located in MAMP/logs/php/php_error.log
Fixed the errors and the message from wordpress went away on activation.
I had the same problem and I just changed the private function to static and it's solved.
private function db_setup() { ....
to
static function db_setup() { ....
I hope this be helpful...
In my case I had added extra blank space before start <?php tag, what a wired error though
In my case, i forget to delete var_dump inside my __construct(). I just delete it and the warn not appear anymore.
I had this same issue. In my case, I was creating some tables when this error occurred. After further digging, I realized that I had this error happening when activating my plugin which then creates the tables.
Error Code: 1060. Duplicate column name 'stadium_id'
A simple mistake as you can see. However, because it threw an error, it caused the same header output error (“headers already sent” messages, problems with syndication feeds or other issues, try deactivating or removing this plugin.) to display on the plugin page after activating.
Final thoughts, ensure that your code is not triggering any errors as this will and can cause the issue! Also, do not echo a message when using the register_activation_hook as already mentioned by T.Todua. Instead, use the admin_notices hook. https://developer.wordpress.org/reference/hooks/admin_notices/

The plugin generated X characters of unexpected output during activation (WordPress)

I'm getting this message each time I activate my plugin:
The plugin generated 80 characters of unexpected output during activation. If you notice “headers already sent” messages, problems with syndication feeds or other issues, try deactivating or removing this plugin.
The only way I was able to suppress the message was to wrap my activation function code within an if statement (please refer to snippets below).
Here, a snippet of my plugin code when I get the error described above:
function myPlugin( $post ) {
echo "Whatever is here throws an unexpected output alert when the plugin isa activated";
}
register_activation_hook( __FILE__, 'myPlugin' );
Following, my wrapping the function in my plugin within an if statement; it suppresses the previous error as discussed above:
function myPlugin( $post ) {
global $pagenow;
if ( is_admin() && $pagenow !== 'plugins.php' ) {
echo "No more alerts when its wrapped this way";
}
}
}
register_activation_hook( __FILE__, 'myPlugin' );
What actually cause that error and how can I effectively complete my plugin with my logics without having to encounter it?
Is there any better way to handle this?
2 probably reasons:
1) You are doing an output (like echo or etc) in wrong place.
Do you want to output a message in admin dashboard? - use admin_notices hook and output there...
Do you want to output a message in front-end? - find appropriate places with hooks (like the_content or wp_footer or whatever).
Don't output anything either in register_activation_hook or outside of WordPress standard hooks, no-one should do that.**
2) if you aren't doing any output intentionally, then maybe some php error happens? If so, put this code temporarily in functions.php and then activate the plugin - you will see the error.
define('temp_file', ABSPATH.'/_temp_out.txt' );
add_action("activated_plugin", "activation_handler1");
function activation_handler1(){
$cont = ob_get_contents();
if(!empty($cont)) file_put_contents(temp_file, $cont );
}
add_action( "pre_current_active_plugins", "pre_output1" );
function pre_output1($action){
if(is_admin() && file_exists(temp_file))
{
$cont= file_get_contents(temp_file);
if(!empty($cont))
{
echo '<div class="error"> Error Message:' . $cont . '</div>';
#unlink(temp_file);
}
}
}
Had the same error, but only with 6 characters )
so... in my case I had empty lines after PHP closing tag ?> - that will cause this error too.
I think there may be two issues here that are causing the problem. First is that I don't think wordpress expects any output when the plugin activation hook is called so it may be complaining about that. Second is that plugin activation hooks are called fairly early in the wordpress program flow, so, it's probably being called before headers are sent. If ANY output is generated before calling header() then PHP usually complains.
Usually the plugin activation routine is reserved for basic setup of the plugin, calls to things like set_option() and the like.
I had the same error - 3 characters of unexpected output and was lead here. For people in my scenario another cause of this message can be the file type being encoded as UTF with BOM.
BOM encoding was causing the error, and while the plug-in activated it would render incorrectly in internet explorer because of this.
The solution is to use Notepad++ and choose 'Convert to UTF without BOM', or if you are using visual studio, there is an explanation of how to change encoding UTF-8 without BOM
I battled this problem for a long time. Typically this is caused by spaces or new lines before the opening <?php tag or after the closing ?> tag. Once I removed these, the error went away.
Also, never assume anything about GET, POST, COOKIE and REQUEST variables. Always check first using isset() or empty().
In my case it was due to Undefined index, Just enable the debug log to check whats causing it, then you can resolve it easily.
For those who don't know how to enable the Debug log, Add these lines in your wp-config.php:
define( 'WP_DEBUG', true );
define( 'WP_DEBUG_DISPLAY', true );
define( 'WP_DEBUG_LOG', true );
You can see the errors properly in the debug file created in wp-content
sometime it is because you use <?php ;?> unnecessary or use it like shown below
;?>
<?php
this extra line between closing and starting tag may also cause this error, simple remove that line/space
A common way to assign the register_activation_hook is using a static method of a class. This ensures that your plugin activation function name won't collide with other plugins.
class Foo_Plugin
{
public static function plugin_activation() {
// activation logic
}
}
This function needs to be public and not private. A mistake is easily made though, so this could be a reason for your problems when getting this kind of error.
You would then register the activation with this code in the main plugin file.
register_activation_hook( __FILE__, array( 'Foo_Plugin', 'plugin_activation' ) );
The error message The plugin generated *X* characters of unexpected output during activation is not very helpful or at least not quite enough.
To help locate the issue, add these to wp-config.php:
define( 'WP_DEBUG', true );
define( 'WP_DEBUG_LOG', true );
Then check wp-content/debug.log for more detailed error messages as to the origin of the error.
I had the same problem. I noticed that there were new lines at the beginning of the file. So I removed them and the errors disappeared. Try removing the new lines at the beginning of your files. That may help.
For beginner level developer its must be empty line break after "?>" closing of php tags.
Try removing all empty line break after this.
This problem can be solved by removing extra whitespaces. I solved this problem for my code. You can remove extra whitespaces easily in Adove Dreamweaver.
First, goto edit->Find and Replace. Or press Ctrl+F. Check "Use Regular Expression" button from "option" section.
Fill "find" field with the below code
[\r\n]{2,}
Fill "Replace" field with the below code
\n
Now click on "Replace All" button.
Hope It will work.
I was having the same issue, i tried to remove the code and did everything but still the same problem
the real solution for me was the following.
at the end of the file which contains the header of the plugin i removed closing php ?> and the problem will be solved
at the end of the plugin file which contains the header of the plugin remove the extra line breaks after the closing php ?>
my plugin file ended at line 69 and there were 7 more spaced after the last php code so in the editor the file was up to 66, my error was "The plugin generated 7 characters of unexpected...." when i removed extra lines up to 69 the was error gone,
Thanks
First sight checklist for unexpected output error on plugin.
Remove closing php tag ?> in all php file of plugin.
Remove empty space before php tag <?php
Avoid echo content in function/hook otherwise clean buffer when needed.
check here to see more info you can use:
<?php
include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
If (is_plugin_active('wshops/init.php'))
{
//Run your plugin includes files or functions
}
in your init php file.
i also got this problem when i activate my plugin
The plugin generated 1 characters of unexpected output during activation. If you notice “headers already sent” messages, problems with syndication feeds or other issues, try deactivating or removing this plugin.
Typically this is caused by spaces or new lines before the opening tag. Once I removed these, the error went away.
now my plugin error gone.
My problem was that in the main php file, i had appended at the end of the file a javascript function. It seems that wordpress hooks such of a function in the head element. I externalised that function into a java script file.
Before:
<?php
/**
* Plugin Name: yyy
* Description: yyy
* Author: yyy
* Author URI: yyy
* Version: yyy
*/
/* many functions here */
function insert_in_header() {
echo '<script type="text/javascript">',
"perform_redirection(", '"', get_option('root'), '"', ", ", '"', get_option('redirect_to'), '");',
'</script>';
}
add_action('wp_head', 'insert_in_header');
?>
<--! PROBLEMS HERE-->
<script type = "text/javascript">
function perform_redirections(root, redirectionLink) {
// code here
}
</script>
After:
<?php
/**
* Plugin Name: yyy
* Description: yyy
* Author: yyy
* Author URI: yyy
* Version: yyy
*/
/* many functions here */
function insert_in_header() {
// in headscripts.js i put the perform_redirection function
echo '<script type="text/javascript" src="', plugins_url('js/headscripts.js', __FILE__ ), '"> </script>';
echo '<script type="text/javascript">',
"perform_redirection(", '"', get_option('root'), '"', ", ", '"', get_option('redirect_to'), '");',
'</script>';
}
add_action('wp_head', 'insert_in_header');
?>
For me there was some kind of error which was being swallowed and not caught during debug
If ound this article here which explains how to determin what this output actually is
$unexpectedOutput= ob_get_contents();
now you have it, you can echo it or inspect it during debug to find out what the hells going wrong, for me it was a prolem with a database script.
Credit to the article below
https://www.toddlahman.com/the-plugin-generated-x-characters-of-unexpected-output-during-activation/
just make the function static which your are calling on activation hook
Opening the PHP file in Notepad and saving it with ANSI encoding did the trick for me. It did not cause the issue to happen again even when I opened and saved it later in Visual Studio Code.
Thanks to Todd
After trying every answer and still coming short, I figured out my issue which was different to all answers here.
Basically, the unexpected characters were coming from my error log on the MAMP server. The errors weren't displaying on frontend or Wordpress installation error log, even with WP_DEBUG, WP_DEBUG_DISPLAY and display_errors = On in the php.ini
I eventually knew it was an error causing the umm error, so I dug a bit deeper and found some errors in my php_error.log which is located in MAMP/logs/php/php_error.log
Fixed the errors and the message from wordpress went away on activation.
I had the same problem and I just changed the private function to static and it's solved.
private function db_setup() { ....
to
static function db_setup() { ....
I hope this be helpful...
In my case I had added extra blank space before start <?php tag, what a wired error though
In my case, i forget to delete var_dump inside my __construct(). I just delete it and the warn not appear anymore.
I had this same issue. In my case, I was creating some tables when this error occurred. After further digging, I realized that I had this error happening when activating my plugin which then creates the tables.
Error Code: 1060. Duplicate column name 'stadium_id'
A simple mistake as you can see. However, because it threw an error, it caused the same header output error (“headers already sent” messages, problems with syndication feeds or other issues, try deactivating or removing this plugin.) to display on the plugin page after activating.
Final thoughts, ensure that your code is not triggering any errors as this will and can cause the issue! Also, do not echo a message when using the register_activation_hook as already mentioned by T.Todua. Instead, use the admin_notices hook. https://developer.wordpress.org/reference/hooks/admin_notices/

Categories