WordPress.org

Ready to get started?Download WordPress

Forums

Plugin Dev: Using Settings API with class (7 posts)

  1. digitaldonkey
    Member
    Posted 3 years ago #

    After a loooong session I finally go the Settings-Api working with a class.
    Maybe it's usefull for Plugin Developers who wanna use the Settings API.

    Comments Welcome :)
    [Code moderated as per the Forum Rules. Please use the pastebin]

  2. iLightning
    Member
    Posted 3 years ago #

    thanks d-monkey. Do you know of a way to pass a variable into the function called 'admin_display_settings' above? Working toward a similar approach for theme development but it's not objected oriented at the moment. I'm just looping through a multidimensional array I built to create the needed admin pages.

    Thanks!

  3. iLightning
    Member
    Posted 3 years ago #

    whoops, meant d-donkey. Hopefully you can get that class uploaded, I was just coming back to take a closer look =)

  4. digitaldonkey
    Member
    Posted 3 years ago #

    I don't know which rules I violated, but I pasted the code here and I don't know wehere else.

    @Moderator: I posted code here to enable seraching for the functions-names please dont REMOVE it, but MOVE it! Next time I'll use the pastbim, but I didn't know about yet.

    @ILightning: I don't have it anymore (thats why I posted it here ... ). Please ask the Moderator.

  5. helgatheviking
    Member
    Posted 3 years ago #

    So you now longer have this code? Damn, it sounded like exactly what i need to integrate the settings API into my theme options

  6. digitaldonkey
    Member
    Posted 3 years ago #

    Sorry, can't find the published Version, but it's about the following. Would be nice if the Anonymus moderator who deleted it can show where he put it.

    You can see the code and the implementation in the loaded classes at the wpg3-git

    It's about this:

    /**
       *   Options Page and Input Validation for WPG3-Modules
       *
       *   Depends on WP-Settings Api
       *
       *    {@source}
       *
      **/
      public function wpg3_admin_init()
      {
        global $wp_rewrite;
    
        // MODULES register their options here
        $modules = array($this->get_module() );
        if($this->is_enabled){
    
          $xhttp = $this->get_module_instance('WPG3_Xhttp');
          array_push($modules, $xhttp->admin_init() );
    
          $template = $this->get_module_instance('WPG3_Template');
          array_push($modules, $template->admin_init() );
          /*
          $imagechoser = $this->get_module_instance('WPG3_Imagechoser');
          array_push($modules, $imagechoser->admin_init() );
          */
          if ( $wp_rewrite->using_permalinks() ){
            $gallerypage = $this->get_module_instance('WPG3_Rewrite');
            array_push($modules, $gallerypage->admin_init() );
          }
        }
    
        register_setting(
          'wpg3_options_grp', // settings group
          'wpg3_options', // settings
          array(&$this,'admin_validate_options') // fn to validate input
          );
        $page = 'wpg3_options_page';
    
        // load Settings API
        if (!function_exists('add_settings_section')){
          require_once(ABSPATH.'wp-admin/includes/template.php');
        }
        /* stores validation functions */
        $this->validate_fields = array();
        //  setting Option sections and fields
        foreach( $modules as $module){
          if ( $module ){
            add_settings_section( $module['unique_name'], $module['title'], $module['function'], $page);
            if( isset($module['settings_fields']) ){
              foreach($module['settings_fields'] as $field){
               add_settings_field($field['field_id'], $field['field_title'], $field['field_display'], $page, $module['unique_name']);
               if( isset($field['field_validate']) )$this->validate_fields[ $field['field_id'] ] = $field['field_validate'];
              }
            }
          }
        }
      }
    
    /**
      *   get a module instance, load if required
      *
      *   {@source}
      *
      *   @param string Classname
      *   @return object instance
     **/
      public function get_module_instance($module, $override_options = false){
        $return = false;
        if (isset($this->modules[$module]) and !$override_options){
          $return = $this->modules[$module];
        }else{
          if (! isset($this->modules[$module])) $this->__autoload( $module );
          if ( $override_options){
            $this->wpg3_options = $override_options;
          }
          $instance = new $module( $this->wpg3_options );
          $this->modules[$module] = $instance;
          $return = $instance;
        }
       return $return;
      }
    
    /**
      *   Create Options Page for WPG3
      *   @internal
     **/
      public function admin_add_page()
      {
        add_options_page(__('WPG3 Settings'),
                         __('WPG3'),
                         'manage_options',
                         __('WPG3'),
                         array(&$this,'admin_optins_page_fn')
                         );
      }
    
    /**
      *   Echo Option Page
      *   @internal
     **/
      public function admin_optins_page_fn()
      {
        //echo "This is the admin_optins_page() ";
        echo "\n<div>\n";
        echo '<h2>'.__('WPG3 Settings')."</h2>\n";
        echo '<form action="options.php" method="post">'."\n";
        settings_fields('wpg3_options_grp'); // Group Name
        echo "\n";
        do_settings_sections('wpg3_options_page');
        echo "\n";
        echo '<p><input name="Submit" type="submit" value="'. __('Save Changes').'" /></p>'."\n";
        echo "</form>\n</div>\n";
      }
    
    /**
      *   Validate Option Fields
      *
      *   @param array WP-secured Input from $_POST
      *   @return array Input validated
     **/
      public function admin_validate_options($input)
      {
        $wpg3_options = $this->wpg3_options;
    
        $validatable = array_intersect_key( $this->validate_fields,  $input);
    
        foreach ($validatable as $field => $function){
          $val = call_user_func ($function, $input[$field]);
          if( $val) $wpg3_options[$field] = $val;
       }
        return $wpg3_options;
      }		
    
    /**
     *  Every Module can provide its own Options or return "false"
     *
    **/
      private function get_module(){
         $main_mudule = array(
                    // unique section ID
                    'unique_name' =>'main_options',
                    // visible Section Title
                    'title' => __('Basic WPG3 Options'),
                    // callback_fn displaying the Settings
                    'function' => array( $this , 'admin_options_section_display' ),
                    // FIELDS
                    'settings_fields' => array(
                                            array(
                                            // unique ID
                                            'field_id' => 'g3Url',
                                            // field TITLE text
                                            'field_title' => __('Gallery3 Url'),
                                            // function CALLBACK, to display the input box
                                            'field_display' => array( $this , 'admin_options_section_display_g3Url'),
                                            // function CALLBACK validate field
                                            'field_validate' => array( $this , 'admin_options_section_validate_g3Url')
                                           ),
                                            array(
                                            // unique ID
                                            'field_id' => 'g3Resize',
                                            // field TITLE text
                                            'field_title' => __('Resize Options'),
                                            // function CALLBACK, to display the input box
                                            'field_display' => array( $this , 'admin_options_section_display_g3Resize'),
                                            // function CALLBACK validate field
                                            'field_validate' => array( $this , 'admin_options_section_validate_g3Resize')
                                           )
                                   )
              );
        return $main_mudule;
      }
    
    /**
     *  Section Header for Options Page
     *
    **/
      public function admin_options_section_display()
      {?>
        <div style="width: 600px; margin-left: 10px;">
    
        <p>
           You must enable REST-Module in Gallery3 in Order to use WPG3.
        </p>
        </div>
    
    <?php }
    
    /**
     *  Options Page Output for "g3Resize"
     *
     *  @todo Pass the Width-param from WPG3-Tag to Template
    **/
      public function admin_options_section_display_g3Resize()
      {
        $options = $this->wpg3_options; 
    
        $field_id = 'g3Resize';
        $val = isset($options[$field_id])? $options[$field_id] : array('max_thumb' => 100, 'max_resize' => 300) ;
        ?>
        <p style = "width:600px;">Gallery 2 <strong>offered custom Resizes</strong>. Gallery3 not yet.<br />
           You can chose which reize to use in WPG3 for the width parameter in WPGX-Tags<br />
           <strong>Note:</strong><em> The Numbered width paramater is available in the Template to adjust width by CSS.</em>
        </p>
        <table >
          <tr>
            <td style = "text-align: right;">Max pixel width<br />to use Thumb</td>
          <?php
            echo '<td><input id="'.$field_id.'[max_thumb]" name="wpg3_options['.$field_id.'][max_thumb]" size="10" type="text" value="'.$val['max_thumb'].'" /> px</td>'."\n";
            echo '<td style = "text-align: center;">Max pixel width<br />to use Medium</td>';
            echo '<td><input id="'.$field_id.'[max_resize]" name="wpg3_options['.$field_id.'][max_resize]" size="10" type="text" value="'.$val['max_resize'].'" /> px</td>'."\n";
          ?>
          <td>For higher width values<br />we use the Fullsize Image</td>
        </tr>
       </table>
       <p>According to this settings WPG3 will chose the
       'thumb', 'resize' or 'full' G3-Image to be inserted for a width parameter</p>
    <?php
      }
    
    /**
     *  Validation Page Validation for "g3Resize"
     *
    **/
      public function admin_options_section_validate_g3Resize($field_val)
      {
       $return = isset($this->wpg3_options['g3Resize']) ? $this->wpg3_options['g3Resize'] : array('max_thumb' => 60, 'max_resize' => 500 );
        if ( is_array($field_val)){
    
          if ( intval( $field_val['max_thumb']) > 0  and intval( $field_val['max_resize'] ) > $field_val['max_thumb']){
            $return['max_thumb'] = $field_val['max_thumb'];
          }else{
          add_settings_error('g3Resize',
                             'settings_updated',
                             __('The Thumb width must be lower than the Medium width @ g3Resize<br /> You entered:<br /> max_thumb = '.$field_val['max_thumb'].'px<br />max_resize = '.$field_val['max_resize'].'px'));
          }
          if ( intval( $field_val['max_resize']) > 0 and $field_val['max_resize'] > $return['max_thumb'] ){
           $return['max_resize'] = $field_val['max_resize'];
          }
        }
        return $return;
      }
    
    /**
     *  Options Page Output for "g3Url"
     *
    **/
      public function admin_options_section_display_g3Url()
      { $field_id = 'g3Url';
        $options = $this->wpg3_options; // we should use data of $this !! ?>
        <p>The Url of you Gallery3 installation
           e.g. <strong>http://wpg3.local/gallery3/index.php</strong>
        </p>
        <?php
        $val = isset($options[$field_id])?$options[$field_id]:get_bloginfo('url').'/gallery3/index.php';
        !$this->is_enabled ? $enabled = ' style="color: red;" ': $enabled ='';
        echo '<input id="'.$field_id.'" name="wpg3_options['.$field_id.']" '.$enabled.'size="60" type="text" value="'.$val.'" />'."\n";
      }
    
    /**
     *  Validate field "restReqestKey"
     *
     *  @todo validate g3Url against REST
    **/
      public function admin_options_section_validate_g3Url($field_val)
      {
        $return = false;
        // validate input
        if ( preg_match('#^http\\:\\/\\/[a-z0-9\-]+\.([a-z0-9\-]+\.)?[a-z]+#i', $field_val)){
            if( substr( $field_val, -1 ) === "/" ) $field_val = substr ( $field_val, 0 , -1 );
            // unset REST API Key
            unset($this->wpg3_options['restReqestKey']);
            $return = $field_val;
        }else{
          // create a nice Error including you field_id
          add_settings_error('g3Url',
                             'settings_updated',
                             __('A valid Gallery3 Url is required @ g3Url<br /> You entered: "'.$field_val.'"'));
        }
        return $return;
      }
    
      private function __autoload($class_name) {
        include 'wpg3_class_'.$class_name . '.php';
      }
    /**
     *  Get WPG3 Options
     *  @return array wpg3_options
    **/
    	public function get_options() {
        return $this->wpg3_options;
      }
    /**
     *  WPG3 enabled?
     *  @return bool true/false
    **/
      public function is_enabled($type){
        $return = false;
        if (isset($this->wpg3_options[$type]) and $this->wpg3_options[$type] == "enabled") $return = true;
        return $return;
      }
    
    }// END class WPG3_Main
    
    	add_action('init', array(&$wpg3, 'wpg3_init') );
    	add_action('admin_init', array(&$wpg3, 'wpg3_admin_init') );
       /* Add options Page */
        add_action('admin_menu', array(&$wpg3, 'admin_add_page') );
      if($wpg3->is_enabled){
        add_filter('the_content', array(&$wpg3, 'wpg3_content_callback') );
     }
  7. helgatheviking
    Member
    Posted 3 years ago #

    thanks for posting this!

Topic Closed

This topic has been closed to new replies.

About this Topic