

If you’re developing custom WordPress plugins and encounter this error in your logs:
PHP Fatal error: Uncaught Error: [] operator not supported for strings in /path/to/plugin.php:104
You’re likely trying to append to a variable that’s a string instead of an array.
## The Problem
This error commonly occurs when using WordPress filters that expect arrays. Here’s the problematic code:
function my_custom_function($post_types) {
$post_types[] = 'my_custom_post_type'; // Fatal error if $post_types is a string!
return $post_types;
}
add_filter('some_filter', 'my_custom_function');
The issue is that some WordPress filters might pass a **string** or **null** instead of an array, causing PHP to throw a fatal error when you try to use the `[]` array append operator.
## The Solution
Always validate that the parameter is an array before trying to append to it:
function my_custom_function($post_types) {
// Ensure $post_types is an array
if (!is_array($post_types)) {
$post_types = array();
}
$post_types[] = 'my_custom_post_type';
return $post_types;
}
add_filter('some_filter', 'my_custom_function');
Real-World Example: Jetpack Stats Integration
I encountered this error while adding Jetpack Stats support to a custom post type. Here’s the fixed code:
// Enable Jetpack Stats for custom post type
function wpm_jetpack_stats_post_types($post_types) {
// Ensure $post_types is an array
if (!is_array($post_types)) {
$post_types = array();
}
if (!in_array('watch_project', $post_types)) {
$post_types[] = 'watch_project';
}
return $post_types;
}
add_filter('stats_array', 'wpm_jetpack_stats_post_types');
add_filter('jetpack_relatedposts_filter_post_type', 'wpm_jetpack_stats_post_types');
Best Practices
When working with WordPress filters and hooks:
- Always validate input types – Don’t assume filters will pass the expected data type
- Use `is_array()`checks before array operations
- Check for duplicates with `in_array()` to avoid adding the same value multiple times
- Test thoroughly – Check your error logs regularly during development
Key Takeaways
- The `[]` operator only works on arrays, not strings or other types
- WordPress filters can sometimes pass unexpected data types
- Always add type checking before manipulating filter parameters
- A simple `is_array()` check can prevent fatal errors
This small defensive coding practice will save you from mysterious fatal errors and make your plugins more robust!