WordPress插件配置保存失效及Illegal string offset警告问题求助
Hey there, let's figure out why your plugin settings aren't saving and fix that PHP warning at the same time.
First, let's break down the warning: Illegal string offset 'show_photos' means that when the code tries to access $input['show_photos'], the $input variable isn't an array—it's a string. That's causing the warning, and it's almost certainly why your settings aren't actually saving (the code hits this error and bails out before completing the save process).
Here's how to fix this step by step:
1. Fix the immediate warning in the code
The line 283 in mstw-tr-settings.php assumes $input is always an array and that the $key exists in it, which isn't the case here. Let's add some safety checks before processing:
Replace the original line:
$output[$key] = ( sanitize_text_field( $input[$key] ) == $input[$key] ) ? $input[$key] : $output[$key];
With this code that adds type and existence checks:
// Only process if $input is an array and the key exists if ( is_array( $input ) && isset( $input[$key] ) ) { $output[$key] = ( sanitize_text_field( $input[$key] ) == $input[$key] ) ? $input[$key] : $output[$key]; } // If $input isn't an array or the key is missing, we keep the existing $output value
This prevents the warning by only accessing $input[$key] when it's safe to do so, ensuring the save logic completes properly.
2. Root cause check: Why is $input a string?
The warning is a symptom—we should also fix why $input isn't an array in the first place. Most likely, this is a form field naming issue in the plugin's settings page:
- Make sure all your settings form fields use array-style names, like
name="mstw_tr_settings[show_photos]"(replacemstw_tr_settingswith your plugin's actual settings array name). If a field uses a plain string name instead of an array, the$_POSTdata will be a string instead of an array when submitted. - Double-check the default settings initialization in the plugin. If the default
$outputarray has a value forshow_photosthat's a string instead of matching the expected input type (like a boolean or text), that could also cause mismatches during save.
3. Test the fix
After making these changes:
- Clear your WordPress debug log (delete the existing
debug.logfile) - Go back to the plugin settings page, make a change, and save
- Check if the settings actually stick now, and verify no new warnings appear in the debug log
That should resolve both the warning and the settings not saving issue.
内容的提问来源于stack exchange,提问作者Damian Busz

