オプション廻りの取り扱いに関するクラス

コード

<?php
class WPMOPOptions {

    private static $_this;
    private $options;

    private function __construct()
    {
        //オプションデータはまとめて全部取得しておく
        $this->options = (array) get_option('wpmop-options');
        //メソッドはsave, get_value, set_value
    }

    public static function get_instance()
    {
        self::$_this = empty( self::$_this ) ? new WPMOPOptions() : self::$_this;
        return self::$_this;
    }

    public function get_value( $key, $default = '' )
    {
        if( isset( $this->options[$key] ) ):
            return $this->options[$key];
        endif;

        return $default;
    }

    public function set_value( $key, $value )
    {
        $this->options[$key] = $value;
        return $this;
    }

    public function save()
    {
        update_option( 'wpmop-options', $this->options );
    }

    public function create_textfield( $args )
    {
    //準備中
    }

    public function create_textfield_long( $args )
    {
    //準備中
    }

    public function create_textfield_short( $args )
    {
    //準備中
    }

    public function create_textarea( $args )
    {
    //準備中
    }

    public function create_selectbox( $args )
    {
    //準備中
    }

    public function create_checkbox( $args )
    {
    //準備中
    }

    public function create_radiobox( $args )
    {
    //準備中
    }

}

使用例

//Optionsクラスのインスタンス化
$wpmop_options = WPMOPOptions::get_instance();

//widthの値を取得
$wpmop_options_width = $wpmop_options->get_value( 'width' );

//widthの値を設定
$wpmop_options->set_value( 'width', '500px' );

//設定しただけでは保存されないので保存処理
$wpmop_options->save();

Posted by webmaster