Created
March 31, 2016 16:38
-
-
Save leobaiano/67a0841fff485edd2c9d3fa71320229a to your computer and use it in GitHub Desktop.
Exemplo de classe para criar campos personalizados usando a Settings API do WordPress
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
if ( ! defined( 'ABSPATH' ) ) | |
exit; // Exit if accessed directly. | |
/** | |
* Pimap Options. | |
* | |
* @package Pimap/Admin | |
* @category Admin | |
* @author Leo Baiano <leobaiano@lbideias.com.br> | |
*/ | |
class Options_Meu_Plugin { | |
/** | |
* Instance of this class. | |
* | |
* @var object | |
*/ | |
protected static $instance = null; | |
/** | |
* Plugin settings. | |
* | |
* @var array | |
*/ | |
public $plugin_settings = array(); | |
/** | |
* Initialize the plugin | |
*/ | |
public function __construct() { | |
// Adds admin menu. | |
add_action( 'admin_init', array( $this, 'settings_section_options' ) ); | |
} | |
/** | |
* Creating the options section and fields of plugin options | |
* | |
*/ | |
public function settings_section_options() { | |
add_settings_section( | |
'meu_plugin_section', | |
__( 'Opções do plugin', 'meu-plugin' ), | |
'__return_false', | |
'meu_plugin_options' | |
); | |
add_settings_field( | |
'desconto_plus', | |
__( 'Desconto Plus', 'meu-plugin' ), | |
array( $this, 'text_element_callback' ), | |
'meu_plugin_options', | |
'meu_plugin_section', | |
array( | |
'name' => 'meu_plugin_plus', | |
'id' => 'meu_plugin_plus', | |
'class' => 'input_text', | |
'settings' => 'meu_plugin_settings_main' | |
) | |
); | |
// Repete o add_settings_field para criar os outros campos | |
register_setting( 'meu_plugin_settings', 'meu_plugin_settings_main' ); | |
} | |
/** | |
* Callback to create fields of type text | |
* | |
* @param array $args Data required for the creation of the field | |
* @return string HTML field | |
*/ | |
public function text_element_callback( $args ){ | |
$name = $args['name']; | |
$id = $args['id']; | |
$class = $args['class']; | |
$settings = $args['settings']; | |
$valueArr = get_option( $settings, array() ); | |
if( isset( $valueArr[$name] ) ) | |
$value = $valueArr[$name]; | |
else | |
$value = ''; | |
echo sprintf( '<input type="text" id="%2$s" name="%4$s[%1$s]" value="%5$s" class="%3$s" />', $name, $id, $class, $settings, $value ) . ' % '; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment