Disclaimer, I've only been doing Wordpress/PHP for a few weeks, so feel free to REALLY break things down for me.
I've been working on building a settings page for my custom Wordpress plugin. My plugin has all of its functions living in classes, so I am doing things like this:
add_action('init', array($this, 'custom_func'));
instead of
add_action('init', 'custom_func');
I think this is working because the second argument for add_action accepts an array OR the string name of a function OR an anonymous function.
My current issue is that I can't get this to work for my settings page.
The code:
public function plugin_admin_init () {
//Register group of options
register_setting( 'exp_wp_plugin_options', 'exp_wp_plugin_options', array( $this, 'plugin_options_validate' ) );
//Add a section to group
add_settings_section('exp_wp_plugin_main', 'Main Settings', function () {
//plugin_settings_text
echo '<p>Main description of this section here.</p>';
}, $this->screen );
//Add a field to the section
add_settings_field('exp_wp_plugin_text_string', 'Plugin Text Input', array( $this, 'plugin_setting_string' ), $this->screen, 'plugin_main');
}
public function plugin_setting_string() {
$options = get_option('plugin_options');
echo "<input id='plugin_text_string' name='plugin_options[text_string]' size='40' type='text' value='{$options[ 'text_string' ]}' />";
}
The
register_settingsfunction call allows me to pass the array($this, 'func_name') syntaxThe second function call,
add_settings_section, is working using an anonymous function (but I'd rather move this to another method if possible).The third function,
add_settings_field, is failing using the array($this, 'func_name') syntax, and the error being thrown is that it's looking for a string.
These methods are part of WP's Settings API. I'm not sure if this is a PHP problem, or a Wordpress problem, but if anyone can tell me how to get this working, I'd appreciate any help.
EDIT: This is the error my IDE (PHP Storm) is throwing:
Expected string, got array. Invocation parameter types are not compatible with declared.
callable, so PHPStorm shouldn't give you a warning about it. This was changed on Feb 23rd, 2016, before that it was indeed type hinted asstring. This change was first included in Wordpress 4.5, released in April 2016. - rickdenhaan