wordpress-settings-api-class icon indicating copy to clipboard operation
wordpress-settings-api-class copied to clipboard

The procedural example does not work.

Open nextgenthemes opened this issue 7 years ago • 2 comments

I cloned this repo and replaced the oop-example include with the procedural file and it does not work.

The way that you just create a new instance make no sense to me but I have not looked at now the class works.

You should actually test it and include a test that is executed by default for it.

nextgenthemes avatar Mar 31 '17 15:03 nextgenthemes

I noticed the same thing. I modified the class to return a Singleton and adapted the corresponding part in my plugin file:

class.settings-api.php:

    protected function __construct() {
        add_action( 'admin_enqueue_scripts', array( $this, 'admin_enqueue_scripts' ) );

        return self::$instance;
    }

    public static function getInstance() {
        if (!isset(self::$instance)) {
            self::$instance = new self();
        }
        return self::$instance;
    }

myplugin.php:

function myplugin_options_page() {
    $settings_api = WeDevs_Settings_API::getInstance();

    echo '<div class="wrap">';
    settings_errors();

    $settings_api->show_navigation();
    $settings_api->show_forms();

    echo '</div>';
}

// in admin_init() function
function myplugin_admin_init() {
     // ...
    $settings_api = WeDevs_Settings_API::getInstance();
    $settings_api->set_sections($sections);
    $settings_api->set_fields($fields);
    $settings_api->admin_init(); 
}

One has to use WeDevs_Settings_API::getInstance() in the options_page() function because otherwise the initial data from init function is not used.

gruentee avatar Mar 14 '18 15:03 gruentee

Thanks for this addition. Using the class in this manner resulted in a fatal error : Fatal error: Uncaught Error: Access to undeclared static property: WeDevs_Settings_API::$instance

Which was solved by declaring the property in the class first like private static $instance;

sanderdewijs avatar Aug 19 '18 21:08 sanderdewijs