Почему API настроек не сохраняет мой массив опций


Я пишу набор классов для простого создания страниц опций, доступных через подменю стандартных меню WordPress, и способ простого создания опций для указанных меню. Я подключаю его через класс настроек, в который вы передаете настройки, и я намерен заставить его работать вместе с классом подменю, чтобы создать меню, страницу настроек и аккуратно сохранить параметры в одном параметре. Опция создается в базе данных, но ничего не хранится в вариант. Может ли кто-нибудь направить меня в правильном направлении? Вот мой код:

Класс настроек

class settings_page {
    public function __construct($args){
        foreach($args['sections'] as $section){
            $section_name = $section['section_name'];
            $section_id = $section['section_id'];
            if( false == get_option( $section_id ) ) {     
                add_option( $section_id );  
            } 
            $options = get_option($section_id);
            $section_text = $section['section_text'];
            $page = $section['page'];
            add_settings_section($section_id, $section_name, function(){return $section_text;}, $page);
            foreach($section['items'] as $item) {
                $type = $item['type'];
                $id = $item['id'];
                $description = $item['description'];
                $title = $item['title'];
                $choices = $item['choices'];
                if ($description) $title = $title . '<br /><small class="italic">' . $description . '</small>';
                switch($type){
                    case "checkbox":
                        add_settings_field($id, $title, 
                                function ($section) use ($options) {
                                    $id = $section[0];
                                    $html = '<input type="checkbox" id="' . $id . '" name="' . $id . '" value="1" ' . checked(1, $options[$id], false) . '/>';  
                                    echo $html;  
                                },
                        $page, $section_id, array($id));
                    break;
                    case "text":
                        add_settings_field($id, $title, 
                                function ($section) use ($options) {
                                    $id = $section[0];
                                    unset($html);
                                    $html .= '<input type="text" id="' . $id . '" name="' . $id . '" value="' . $options[$id] . '" />';  
                                    echo $html;  
                                },
                        $page, $section_id, array($id));
                    break;
                    case "textarea":
                        add_settings_field($id, $title, 
                                function ($section) use ($options) {
                                    $id = $section[0];
                                    unset($html);
                                    $html .= '<textarea class="large-text" cols="50" rows="10" type="text" id="' . $id . '" name="' . $id . '">' . $options[$id] . '</textarea>';  
                                    echo $html;  
                                },
                        $page, $section_id, array($id));
                    break;
                    case "pulldown":
                        add_settings_field($id, $title, 
                                function ($section) use ($options) {
                                    $id = $section[0];
                                    $choices = $section[1];
                                    $value = $options[$id];
                                    unset($html);
                                    $html = '<select id="' . $id . '" name="' . $id . '">';
                                    $html .= '<option value=""> - Select - </option>';
                                    foreach($choices as $key=>$val){
                                        $selected = '';
                                        if ($value== $key) $selected = ' selected="selected" ';
                                        $html .= '<option value="' . $key . '"' . $selected . '>'.$val.'</option>';
                                    }
                                    $html .= '</select>';

                                    echo $html;  
                                },
                        $page, $section_id, array($id, $choices));
                    break;                  
                }

            }
            register_setting($page, $section_id);
        }

        new submenu(array(
            "parent" => $args['parent'],
            "title"=>$args['title'],
            "text"=>$args['text'],
            "capability"=>$args['capability'],
            "slug"=>$args['slug']

        ));

    }
}

Класс подменю

<?php

class submenu {

    function __construct($args=""){
            $parent = strtolower($args['parent']);
            $title = $args['title'];
            $text = $args['text'];
            $capability = $args['capability'];
            $slug = $args['slug'];

            switch($parent){
                case 'dashboard': 
                    $name = "index.php";
                    break;
                case 'posts':
                    $name = 'edit.php';
                    break;
                case 'media':
                    $name='upload.php';
                    break;
                case 'links':
                    $name='link-manager.php';
                    break;
                case 'pages':
                    $name='edit.php?post_type=page';
                    break;
                case 'comments':
                    $name='edit-comments.php';
                    break;
                case 'appearance':
                    $name='themes.php';
                    break;
                case 'plugins':
                    $name='plugins.php';
                    break;  
                case 'users':
                    $name='users.php';
                    break;  
                case 'tools':
                    $name='tools.php';
                    break;  
                case 'settings':
                    $name='options-general.php';
                    break;  
                default:
                    $name='options-general.php';
                    break;  
            }
            add_action('admin_menu', function() use ($name, $title, $text, $capability, $slug) {

                    add_submenu_page(  
                        $name,                  
                        $title,          
                        $text,                  
                        $capability,            
                        $slug, function() use  ($name, $title, $text, $capability, $slug) {
                       ?>
                            <div class="wrap">  


                                <div id="icon-themes" class="icon32"></div>  
                                <h2><?php echo $title; ?></h2>  
                                <form method="post" action="options.php">  
                                    <?php settings_fields( $slug ); ?>  
                                    <?php do_settings_sections( $slug );?>    
                                    <?php submit_button(); ?>  
                                </form>  

                            </div>

                       <?php
                        }

                    );
                }
            );



        }
    }

Вот где я на самом деле вызываю классы/методы

add_action('admin_menu', 
    function() {
        $options['parent'] = "settings";
        $options['title'] = "My Settings";
        $options['text'] = "My Settings";
        $options['capability'] = "manage_options";
        $options['slug'] = "my_settings";

        $settings['section_name'] = "General Section";
        $settings['section_id'] = "general_section";
        $settings['section_text'] = "This be General Section Test";
        $settings['page'] = "my_settings";
        $settings['items'] = array(
            array(
                'type' => 'checkbox',
                'id' => 'show_header',
                'title' => 'The title, to show header',
                'description' => 'show the header now please',
                ),
            array(
                'type' => 'textarea',
                'id' => 'show_footer',
                'title' => 'The title, to show footer',
                'description' => 'show the footer now please',
                ),  
            array(
                'type' => 'text',
                'id' => 'text_item',
                'title' => 'Enter anything here',
                'description' => '',
                ),          
            array(
                'type' => 'pulldown',
                'id' => 'which_one',
                'title'=>'Who\'s on First?',
                'description'=>'',
                'choices'=>array(
                        '1'=>'Who',
                        '2'=>'What',
                        '3'=>'Why',
                    )
                ),
            );
        $settings2['section_name'] = "Second Section";
        $settings2['section_id'] = "second_section";
        $settings2['section_text'] = "More Settings";
        $settings2['page'] = "my_settings";
        $settings2['items'] = array(
            array(
                'type' => 'checkbox',
                'id' => 'show_header_2',
                'description' => 'Show Second Header',
                'title' => 'Show the Second Header?',
                ),
            array(
                'type' => 'textarea',
                'id' => 'show_footer_2',
                'description' => 'Tell me a story',
                'title' => 'It can be about anything!',
                ),  
            );

        $options['sections'][] = $settings;
        $options['sections'][] = $settings2;
        new settings_page($options);
    }, 1);

Что работает:

Это сработает, если я изменю $options[$id] на get_option($id), но это сохранит каждый отдельный параметр в отдельной настройке в базе данных, что крайне неэффективно. Я заблокировал ошибку $страница, $раздел_id прямо перед вызовом register_setting, и все идет так, как должно быть, что ставит меня в тупик.

Что не работает: сохранение этих настроек в сериализованный массив:)

Я рад предоставить все остальное, что может помочь вам помочь мне.

Спасибо.

Author: setterGetter, 2013-05-09

1 answers

У вас есть параметры имени, установленные в "$id", что означает, что они будут такими, как "show_header_2" и тому подобное. На самом деле вы хотите, чтобы они были "second_section[show_header_2]" и аналогичными, так что массив настроек - это то, что вы получаете из формы.

 6
Author: Otto, 2013-05-11 20:41:15