0

I want to implement a plugin which gets 2 fields in admin area and saves those in options as array
I read the page Custom Settings Page but seems it doesn't describe how to save fields values in options
How we can do it ?

Thank you

<?php

/**
 * Class for registering persian font settings page under Settings.
 */
class PersianFont_Options_Page {

    public $page_title;
    public $menu_title;
    public $plugin_slug;
    public $plugin_hook;

    /**
     * Constructor.
     */
    function __construct() {

        $this->plugin_slug = 'persianfont';
        $this->page_title = __('تنظیمات افزونه فارسی ساز قالب', 'persianfont');
        $this->menu_title = __('فارسی ساز قالب', 'persianfont');

        add_action( 'admin_menu', [ $this, 'add_admin_menu' ] );

        // Here you can check if plugin is configured (e.g. check if some option is set). If not, add new hook.
        // In this example hook is always added.
        add_action( 'admin_notices', [ $this, 'add_admin_notices' ] );

        add_action( 'admin_init',  [ $this, 'register_settings' ] );
    }

    /**
    * Registers a new settings page under Settings.
    */
    function add_admin_menu() {
        $this->plugin_hook = 
            add_options_page(
                $this->page_title,
                $this->menu_title,
                'manage_options', // capability
                $this->plugin_slug,
                [ $this, 'settings_page_content' ] //output the content for this page
        );

        //var_dump($this->plugin_hook); // -> string(26) "settings_page_persian_font"
        if($this->plugin_hook){
            add_action( 'load-' . $this->plugin_hook, [ $this, 'on_plugin_page_load' ] );
        }

    }

    function on_plugin_page_load(){
        remove_action( 'admin_notices', [ $this, 'add_admin_notices' ] );
        $this->add_setting_page_help();
    }

    function add_admin_notices() {
        ?>
        <div id="notice" class="update-nag">
            <?php _e('افزونه فارسی ساز قالب پیکربندی نشده است. ', 'persianfont'); ?>
            <a href="<?php menu_page_url( $this->plugin_slug, true ); ?>"><?php _e('لطفا هم اکنون پیکربندی نمائید.', 'persianfont'); ?></a>
        </div>
        <?php
    }

    function add_setting_page_help(){
        // We are in the correct screen because we are taking advantage of the load-* action (below)
        $help_content = 
            '<p>' . __( 'از این صفحه برای تنظیمات افزونه فارسی ساز قالب استفاده نمائید.', 'persianfont' ) . '</p>' .
            '';

        $screen = get_current_screen();
        //$screen->remove_help_tabs();
        $screen->add_help_tab(
        [
            'id'            => 'persianfont-default',
            'title'         => __( 'Help' ),
            'content'   => $help_content,
        ]);
        //add more help tabs as needed with unique id's

        // Help sidebars are optional
        $screen->set_help_sidebar(
            '<p><strong>' . __( 'For more information:' ) . '</strong></p>' .
            '<p><a href="https://parsmizban.com" target="_blank">' . _( 'بازدید از پارس میزبان' ) . '</a></p>'
        );
    }

    function register_settings() { // whitelist options
        register_setting(
            $this->plugin_slug, // option_group
            $this->plugin_slug, // option_name, for name property of tags
            [$this, 'process_inputs'] // sanitize_callback
        );
            add_settings_section(
                'load-font-setting', // id attribute of tags
                __('تنظیمات مربوط به بارگذاری فونت ها', 'persianfont'), // title heading for the section
                function($args){ ?>
                    <p id="<?php echo esc_attr( $args['id'] ); ?>"><?php _e('با استفاده از تنظیمات زیر، تعیین نمائید که فونت ها برای کدام بخش های سایت بارگذاری شوند.', 'persianfont'); ?></p>
                <?php
                }, // callback function to display content at the top of the section
                $this->plugin_slug // plugin slug, created by add_options_page()
            );
                add_settings_field(
                    'frontend-font', // id attribute of tag
                    __('بارگذاری فونت برای بخش اصلی سایت', 'persianfont'), // Title as lable for field
                    function(){
                        var_dump(get_option( 'persianfont' ));
                        //$check_frontend_font = is_null(get_option( 'persianfont' )['frontend-font']) ? 'true' : get_option( 'persianfont' )['frontend-font'];
                        ?>
                        <input type="checkbox" name="frontend-font" id="frontend-font" value="true" <?php //checked( 'true', $check_frontend_font ); ?> />
                        <?php
                    }, // Callback function to echo input tag
                    $this->plugin_slug, // plugin slug, created by add_options_page()
                    'load-font-setting', // slug-name of the section
                    [
                        'label_for' => 'frontend-font', // label for => tag id
                        'class'     => 'frontend-font', // class for <tr>
                    ]
                );
                add_settings_field(
                    'backend-font', // id attribute of tag
                    __('بارگذاری فونت برای بخش مدیریت', 'persianfont'), // Title as lable for field
                    function(){
                        //$check_backend_font = is_null(get_option( 'persianfont' )['backend-font']) ? 'true' : get_option( 'persianfont' )['backend-font'];
                        ?>
                        <input type="checkbox" name="backend-font" id="backend-font" value="true" <?php //checked( 'true', $check_backend_font ); ?> />
                    <?php
                    }, // Callback function to echo input tag
                    $this->plugin_slug, // plugin slug, created by add_options_page()
                    'load-font-setting', // slug-name of the section
                    [
                        'label_for' => 'backend-font', // label for => tag id
                        'class'     => 'backend-font',  // class for <tr>
                    ]
                );

    }

    /**
     * Sanitize each setting field as needed
     *
     * @param array $input Contains all settings fields as array keys
     */
    public function process_inputs( $input ){
        // sanitize functions:
        // sanitize_email(), sanitize_file_name(), sanitize_html_class(), sanitize_key(), sanitize_meta(), sanitize_mime_type(),
        // sanitize_option(), sanitize_sql_orderby(), sanitize_text_field(), sanitize_textarea_field(), sanitize_title(),
        // sanitize_title_for_query(), sanitize_title_with_dashes(), sanitize_user()
        $options = [];
        if( isset( $input['frontend-font'] ) and $input['frontend-font'] == true ) {
            $options['frontend-font'] = true;
        }else{
            $options['frontend-font'] = false;
        }
        if( isset( $input['backend-font'] ) and $input['backend-font'] == true ){
            $options['backend-font'] = true;
        }else{
            $options['backend-font'] = false;
        }
        //update_option('persianfont', $options);

        // add error/update messages
        // check if the user have submitted the settings
        // wordpress will add the "settings-updated" $_GET parameter to the url
/*      if ( isset( $_GET['settings-updated'] ) ) {
            // add settings saved message with the class of "updated"
            add_settings_error(
                'persianfont_messages', // Slug title of setting
                'wporg_message', // Slug-name , Used as part of 'id' attribute in HTML output.
                __( 'تنظیمات مورد نظر ذخیره شد.', 'persianfont' ), // message text, will be shown inside styled <div> and <p> tags
                'updated' // Message type, controls HTML class. Accepts 'error' or 'updated'.
            );
        }*/
        return $input;
    }

    /**
     * Settings page display callback.
     */
    function settings_page_content() {
        // check user capabilities
        if ( ! current_user_can( 'manage_options' ) ) { return; }

        // var_dump( wp_load_alloptions() ); // print all options

        // show error/update messages
        settings_errors( 'persianfont_messages' );
        ?>
        <div class="wrap">
            <h1 class="wp-heading-inline"><?php echo esc_html($this->page_title); ?></h1>
            <form method="post" action="options.php">
            <?php
                submit_button();
                settings_fields( $this->plugin_slug ); // This prints out all hidden setting fields
                do_settings_sections( $this->plugin_slug );
                submit_button();
            ?>
            </form>
        </div>
        <?php
    }

} // class

new PersianFont_Options_Page;
6
  • It says about Settings API, that's what you can use to create and update the two fields you need.
    – Kumar
    Aug 17, 2017 at 8:43
  • @sven So you mean that it does the saving rules itself? Aug 17, 2017 at 8:44
  • Yeah, Settings API takes care of it.
    – Kumar
    Aug 17, 2017 at 8:47
  • @sven But it doesn't! Aug 17, 2017 at 8:51
  • You can add your code in here, so that I can take a look!
    – Kumar
    Aug 17, 2017 at 8:58

1 Answer 1

1

Something was wrong with the naming, I had to change the field names, and it works ok.

From your code sample, this:

            add_settings_field(
                'frontend-font', // id attribute of tag
                __('بارگذاری فونت برای بخش اصلی سایت', 'persianfont'), // Title as lable for field
                function(){
                    var_dump(get_option( 'persianfont' ));
                    //$check_frontend_font = is_null(get_option( 'persianfont' )['frontend-font']) ? 'true' : get_option( 'persianfont' )['frontend-font'];
                    ?>
                    <input type="checkbox" name="frontend-font" id="frontend-font" value="true" <?php //checked( 'true', $check_frontend_font ); ?> />
                    <?php
                }, // Callback function to echo input tag
                $this->plugin_slug, // plugin slug, created by add_options_page()
                'load-font-setting', // slug-name of the section
                [
                    'label_for' => 'frontend-font', // label for => tag id
                    'class'     => 'frontend-font', // class for <tr>
                ]
            );

should be modified to:

add_settings_field(
        'frontend-font', // id attribute of tag
        __( 'بارگذاری فونت برای بخش اصلی سایت', 'persianfont' ), // Title as lable for field
        function ($args) {

            //$check_frontend_font = is_null(get_option( 'persianfont' )['frontend-font']) ? 'true' : get_option( 'persianfont' )['frontend-font'];
            $persian_font = get_option('persianfont');
            $frontend = !empty( $persian_font ['frontend'] ) ? $persian_font['frontend'] : false;
            ?>
            <input type="checkbox" name="persianfont[frontend]" id="frontend-font"
                   value="true" <?php checked( 'true', $frontend );
            ?> />
            <?php
        }, // Callback function to echo input tag
        $this->plugin_slug, // plugin slug, created by add_options_page()
        'load-font-setting', // slug-name of the section
        [
            'label_for' => 'frontend-font', // label for => tag id
            'class'     => 'frontend-font',    // class for <tr>
        ]
    );

And the other one:

add_settings_field(
        'backend-font', // id attribute of tag
        __( 'بارگذاری فونت برای بخش مدیریت', 'persianfont' ), // Title as lable for field
        function ($args) {
            $persian_font = get_option('persianfont');
            $backend = !empty( $persian_font ['backend'] ) ? $persian_font['backend'] : false;
            //$check_backend_font = is_null(get_option( 'persianfont' )['backend-font']) ? 'true' : get_option( 'persianfont' )['backend-font'];
            ?>
            <input type="checkbox" name="persianfont[backend]" id="backend-font"
                   value="true" <?php checked( 'true', $backend );
            ?> />
            <?php
        }, // Callback function to echo input tag
        $this->plugin_slug, // plugin slug, created by add_options_page()
        'load-font-setting', // slug-name of the section
        [
            'label_for' => 'backend-font', // label for => tag id
            'class'     => 'backend-font',    // class for <tr>
        ]
    );

I've made changes to callback function only.

3
  • I put the $args and get the value using var_dump, it outputs array (size=2) 'label_for' => string 'frontend-font' (length=13) 'class' => string 'frontend-font' (length=13) Aug 17, 2017 at 9:25
  • and also I get this error:Notice: Undefined offset: 0 in D:\xampp\htdocs\wordpress\wp-content\plugins\persian-font\options.php on line 110 Aug 17, 2017 at 9:26
  • @FarhadSakhaei I've added a wrong suggestion, figuring it out, and will update answer soon.
    – Kumar
    Aug 17, 2017 at 9:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.