How to make my plugin code die gracefully

Fatal errors point to bad syntax, or bad naming conventions. WordPress does a good job of not activating plugins that throw fatal errors. However, once a plugin is activated, all bets are off. If you’ve created a function or a class, it’s best to follow good naming conventions and namespace properly.

For example, a function called post_extras() would not be a good name as it most likely would conflict with another badly named function down the road from another plugin. Select a namespace prefix for each plugin that is unique to the plugin itself such as, foobar123_post_extras().

When asking people to embed template tags for your plugin, you should isolate those functions.

if(function_exists('foobar123_post_extras'){
      echo foobar123_post_extras();
}

When declaring classes or functions isolate them this way:

if(!function_exists('foobar123_post_extras'){
     function foobar123_post_extras(){
             //do something
     }
}

if(!class_exists('FooBar123Class'){
      class FooBar123Class{
             //methods
      }
}

This is a best practice for guarding against fatal errors with function and class name conflicts.

If you are including any other file within your plugins, you can certainly minus fatal errors by using the include functions rather than require functions. Check out this article for more information. You could deactivate the plugin if your includes fail like this:

if(!include('includes/foobarinclude.php')){
     $plugins = get_option('active_plugins');
     $index = array_search(plugin_basename(__FILE__), $plugins);
     if($index){
          unset($plugins[$index]);
          update_option('active_plugins', $plugins);
     }
}

WordPress has a good document for coding standards here regarding syntax styling.

Make sure you aren’t using php short tags as they will cause errors on servers that don’t have short tags enabled.

<?= - short tag
<?php echo - proper

For database concerns, always use the $wpdb class when querying the database. You cannot count on users to have the same db prefix that you use.

global $wpdb;
$results = $wpdb->get_results("SELECT * FROM $wpdb->posts WHERE post_type="page" AND post_status="publish" LIMIT 5");

Finally, before releasing a plugin, it’s importing to throw the WP_DEBUG switch in your local environment to see if you are using deprecated WordPress functions or causing other conflicts. If a function disappears in a future release, it certainly will cause fatal problems with your plugin. To use WP_DEBUG, simply add this to your wp-config.php file:

define('WP_DEBUG', true);

Hope this helps give you some clues.