How to debug plugin activation errors in WordPress

If you have ever developed a plugin for WordPress you may remember seeing one of those unhelpful messages saying your plugin generated N characters of unexpected output.

The problem with those messages, apart from not knowing what exactly is what your plugin generated, is that sometimes the errors are not easy to reproduce. You go to your Plugins section, deactivate the plugin in question, try to activate it again and now all you see is “Plugin activated”, no errors.

The last time that happened to me I decided I wanted to see the content of those errors every time they occurred, and I came up with a solution to achieve just that. Is not pretty, but it works. Basically, I stop WordPress execution when this errors occur and show the output in my screen:

Open wp-admin/plugins.php file and look for the part that looks like this (line 42 in WP 3.4 files):

<?php
// more code before...
$result = activate_plugin($plugin, self_admin_url('plugins.php?error=true&plugin=' . $plugin), is_network_admin() );
if ( is_wp_error( $result ) ) {
    if ( 'unexpected_output' == $result->get_error_code() ) {
        $redirect = self_admin_url('plugins.php?error=true&charsout=' . strlen($result->get_error_data()) . '&plugin=' . $plugin . "&plugin_status=$status&paged=$page&s=$s");
        wp_redirect(add_query_arg('_error_nonce', wp_create_nonce('plugin-activation-error_' . $plugin), $redirect));
        exit;
    } else {
        wp_die($result);
    }
}
// more code after

Now add

wp_die($result->get_error_data());

right inside the if that starts with:

if ( 'unexpected_output' == $result->get_error_code() ) {

I know, it’s ugly, but you will be doing it in your development WordPress, so only you would see those errors and that’s the point.

You will have to modify that file again everytime you upgrade your WordPress or you can use a better approach combining this idea with the idea proposed here.

Let me know how do you handle those “unexpected output” error messages.

Related questions in Stack Overflow:

  • DrV

    Thanks so much, will try it with the plugin I’m developing right now :D

  • David Anderson

    Thanks for the post. I tried this but still, all I get is the “Plugin could not be activated because it triggered a fatal error.” Could you please help?

    Thanks alot

    • wvega

      What version of WordPress are you using? I’ll test snippet in that version and see if I can help you.

      • David Anderson

        Hi,
        Thanks for your kind offer. I’m using 3.5.1. I found a solution for my problem. The trick is to add:
        error_reporting(E_ALL ^ E_NOTICE);
        to the index.php of the plugin file.

        All errors were displayed.

  • vitorargos

    This piece of code helped a lot! Thank you!

  • Guest
    • wvega

      Thank you. That’s definitely a cleaner solution!