Foros del Web » Creando para Internet » Sistemas de gestión de contenidos » WordPress »

Problemas de validación y/o inserción en la BD. Setting API

Estas en el tema de Problemas de validación y/o inserción en la BD. Setting API en el foro de WordPress en Foros del Web. Estoy haciendo un setting para un theme, algo parecido al que tiene Twentyeleven, pero una de las funciones no inserta los datos en la base ...
  #1 (permalink)  
Antiguo 12/10/2012, 08:27
Avatar de rogertm
Mod->Cuba
 
Fecha de Ingreso: julio-2005
Ubicación: /home/Cuba/Habana/rogertm/
Mensajes: 2.922
Antigüedad: 18 años, 8 meses
Puntos: 638
Problemas de validación y/o inserción en la BD. Setting API

Estoy haciendo un setting para un theme, algo parecido al que tiene Twentyeleven, pero una de las funciones no inserta los datos en la base de datos.

Lo que tengo es lo siguiente, una función que me permite escoger si en el header del theme aparecerá una imagen de cabecera o no y otra que habilitará unos links a redes sociales, twitter, facebook, etc...

La de la cabecera funciona bien, pero la otra no, aquí parte del código:
Código PHP:
Ver original
  1. <?php
  2. /**
  3.  * Register setting options
  4.  */
  5. add_action( 'admin_init', 'theme_register_setting_options_init' );
  6. function theme_register_setting_options_init(){
  7.     // Based on Twentyeleven WordPress Theme
  8.     register_setting( 'theme_options', 'theme_theme_options', 'theme_theme_options_validate' );
  9.  
  10.     // Register our settings field group
  11.     add_settings_section( 'general', '', '__return_false', 'theme-options' );
  12.  
  13.     // Register our individual settings fields
  14.     add_settings_field( 'theme_header_stuff',    __( 'Header Options', 't_em' ),            'theme_settings_field_header_stuff',            'theme-options',    'general' );
  15.     add_settings_field( 'theme_social_stuff',    __( 'Social Network Options', 't_em' ),    'theme_settings_field_socialnetwork_stuff',    'theme-options',    'general' );
  16. }
  17.  
  18. /**
  19.  * Return an array of header options for Twenty'em
  20.  */
  21. function theme_header_options(){
  22.     $header_options = array (
  23.         'no-header-image' => array (
  24.             'value' => 'no-header-image',
  25.             'label' => __( 'No header image', 't_em' ),
  26.             'extend' => '',
  27.         ),
  28.         'header-image' => array (
  29.             'value' => 'header-image',
  30.             'label' => __( 'Header image', 't_em' ),
  31.             'extend' => theme_header_image_extend(),
  32.         ),
  33.     );
  34.  
  35.     return apply_filters( 'theme_header_options', $header_options );
  36. }
  37.  
  38. /**
  39.  * Return an array of social network options for Twenty'em
  40.  */
  41. function theme_socialnetwork_options(){
  42.     $socialnetwork_options = array (
  43.         'twitter-stuff' => array (
  44.             'value' => '',
  45.             'name' => 'twitter-stuff',
  46.             'label' => __( 'Twitter URL', 't_em' ),
  47.         ),
  48.         'facebook-stuff' => array (
  49.             'value' => '',
  50.             'name' => 'facebook-stuff',
  51.             'label' => __( 'Facebook URL', 't_em' ),
  52.         ),
  53.     );
  54.  
  55.     return apply_filters( 'theme_socialnetwork_options', $socialnetwork_options );
  56. }
  57. ?>
Además, tengo una función que me registra opciones por defecto, otra para obtener las opciones de la BD, otra por cada setting para mostrarlos en el administrador del theme que se las muestro. Esta me imprime en pantalla tres campos de texto donde poner las URLs de las redes sociales:
Código PHP:
Ver original
  1. <?php
  2. /**
  3.  * Render the Socialnetwork setting field
  4.  */
  5. function theme_settings_field_socialnetwork_stuff(){
  6.     $options = theme_get_theme_options();
  7.     foreach ( theme_socialnetwork_options() as $social ) :
  8. ?>
  9.     <div class="layout text-option social">
  10.         <label>
  11.             <span><?php echo $social['label'];?></span>
  12.             <input type="text" name="theme_theme_options['<?php echo $social['name']; ?>']" value="<?php echo esc_attr( $options[$social['name']] ) ?>" />
  13.         </label>
  14.     </div>
  15. <?php
  16.     endforeach;
  17. }
  18. ?>
Y por último una función para validar los datos.
Código PHP:
Ver original
  1. <?php
  2. /**
  3.  * Sanitize and validate input. Accepts an array, return a sanitized array.
  4.  */
  5. function theme_theme_options_validate( $input ){
  6.     $output = $defaults = theme_get_default_theme_options();
  7.  
  8.     // Header stuff must be in our array of header stuff options
  9.     if ( isset( $input['header-stuff'] ) && array_key_exists( $input['header-stuff'], theme_header_options() ) ) :
  10.         $output['header-stuff'] = $input['header-stuff'];
  11.     endif;
  12.  
  13.     // Archive stuff must be in our array of archive stuff options
  14.     if ( isset( $input['archive-stuff'] ) && array_key_exists( $input['archive-stuff'], theme_archive_options() ) ) :
  15.         $output['archive-stuff'] = $input['archive-stuff'];
  16.     endif;
  17.  
  18.     return apply_filters( 'theme_theme_options_validate', $output, $input, $defaults );
  19. }
  20. ?>

El código completo del archivo es mucho más largo, pero me he centrado en solo lo más importante, además tengo un par de cosas más que no me insertan los datos en la BD, pero si resuelvo uno, ya seguro resuelvo lo demás.

Algo más, si elimino el tercer parámetro de la función register_setting(), que es un callback a la función de validación, entonces me guarda los datos, pero por ejemplo, en los campos donde se insertan las URLs de las redes sociales, me manda el siguiente error:
Cita:
Notice: Undefined index: twitter-stuff in /path/to/file/theme-options.php on line 398
que es
Código PHP:
Ver original
  1. <input type="text" name="theme_theme_options['<?php echo $social['name']; ?>']" value="<?php echo esc_attr( $options[$social['name']] ) ?>" />

Para hacer todo esto me estoy guiando por la Settings API y el archivo theme-options.php que viene en Twentyeleven

Gracias mil de antemano a todos los que me puedan dar una ayuda...
__________________
Friki y Blogger por Cuenta Propia:213
Twenty'em: Theming is Prose
  #2 (permalink)  
Antiguo 12/10/2012, 10:25
Avatar de masterpuppet
Software Craftsman
 
Fecha de Ingreso: enero-2008
Ubicación: Montevideo, Uruguay
Mensajes: 3.550
Antigüedad: 16 años, 3 meses
Puntos: 845
Respuesta: Problemas de validación y/o inserción en la BD. Setting API

Que tal rogertm,

Yo de WP ni idea pero es correcto utilizar apply_filters de esa forma ?, tal cual lo tienes no estas generando recursividad ?
__________________
http://es.phptherightway.com/
thats us riders :)
  #3 (permalink)  
Antiguo 12/10/2012, 10:45
Avatar de rogertm
Mod->Cuba
 
Fecha de Ingreso: julio-2005
Ubicación: /home/Cuba/Habana/rogertm/
Mensajes: 2.922
Antigüedad: 18 años, 8 meses
Puntos: 638
Respuesta: Problemas de validación y/o inserción en la BD. Setting API

En algún momento me hice esa misma pregunta, si dejo return $socialnetwork_options; entonces hace lo mismo, osea, no hay cambios. Pero como dije antes, me estoy fijando por el código que hay en Twentyeleven, y si los que saben lo tienen así, pues por algo será

Y acabo de hacer lo siguiente:
Código PHP:
Ver original
  1. /**
  2.  * Return an array of header options for Twenty'em
  3.  */
  4. $header_options = array (
  5.     'no-header-image' => array (
  6.         'value' => 'no-header-image',
  7.         'label' => __( 'No header image', 't_em' ),
  8.         'extend' => '',
  9.     ),
  10.     'header-image' => array (
  11.         'value' => 'header-image',
  12.         'label' => __( 'Header image', 't_em' ),
  13.         'extend' => theme_header_image_extend(),
  14.     ),
  15.     'slideshow' => array (
  16.         'value' => 'slideshow',
  17.         'label' => __( 'Slideshow', 't_em' ),
  18.         'extend' => theme_slider_extend(),
  19.     ),
  20. );
  21. function theme_header_options(){
  22.     theme_ $header_options;
  23.     return apply_filters( 't_em_header_options', $header_options );
  24. }
Y funciona exactamente igual
__________________
Friki y Blogger por Cuenta Propia:213
Twenty'em: Theming is Prose
  #4 (permalink)  
Antiguo 15/10/2012, 07:38
Avatar de masterpuppet
Software Craftsman
 
Fecha de Ingreso: enero-2008
Ubicación: Montevideo, Uruguay
Mensajes: 3.550
Antigüedad: 16 años, 3 meses
Puntos: 845
Respuesta: Problemas de validación y/o inserción en la BD. Setting API

Buenas rogertm, lo pudiste resolver ?, en cualquier caso te hago una pregunta y comentario, la pregunta, en theme_get_default_theme_options tienes definidas las key twitter-stuff - facebook-stuff ? y el comentario, ten en cuenta que tienes '' de mas en el html del input

mal
Código HTML:
Ver original
  1. <input name="theme_theme_options['<?php echo $social['name']; ?>']" />

bien
Código HTML:
Ver original
  1. <input name="theme_theme_options[<?php echo $social['name']; ?>]" />

Saludos.
__________________
http://es.phptherightway.com/
thats us riders :)

Última edición por masterpuppet; 15/10/2012 a las 07:47
  #5 (permalink)  
Antiguo 15/10/2012, 09:37
Avatar de rogertm
Mod->Cuba
 
Fecha de Ingreso: julio-2005
Ubicación: /home/Cuba/Habana/rogertm/
Mensajes: 2.922
Antigüedad: 18 años, 8 meses
Puntos: 638
Respuesta: Problemas de validación y/o inserción en la BD. Setting API

Si si... las comillas de la MUERTE ... Me pasé tres madrugadas en eso

Ahora funciona bien, pero sin la validación, si activo la función de validar el input, algunas cosas se guardan y otras no, tengo que dedicarle un rato a eso a ver si lo termino de resolver, porque aunque no es obligatorio hacer la validación, no está de más...

Gracias...
__________________
Friki y Blogger por Cuenta Propia:213
Twenty'em: Theming is Prose
  #6 (permalink)  
Antiguo 15/10/2012, 09:48
Avatar de masterpuppet
Software Craftsman
 
Fecha de Ingreso: enero-2008
Ubicación: Montevideo, Uruguay
Mensajes: 3.550
Antigüedad: 16 años, 3 meses
Puntos: 845
Respuesta: Problemas de validación y/o inserción en la BD. Setting API

Por eso la pregunta
Cita:
theme_get_default_theme_options tienes definidas las key twitter-stuff - facebook-stuff ?
si no están definidas las claves en las opciones por defecto tienes que hacer algo similar al if de header-stuff y archive-stuff para que quede "registrado" en $output
__________________
http://es.phptherightway.com/
thats us riders :)
  #7 (permalink)  
Antiguo 26/10/2012, 08:01
Avatar de rogertm
Mod->Cuba
 
Fecha de Ingreso: julio-2005
Ubicación: /home/Cuba/Habana/rogertm/
Mensajes: 2.922
Antigüedad: 18 años, 8 meses
Puntos: 638
Respuesta: Problemas de validación y/o inserción en la BD. Setting API

Bueno, desde que publiqué este post hasta hoy han habido algunos cambios, ya me valida bien todo excepto un select, pero creo tener ubicado el problema así que será cuestión de dedicarle un rato...

Finalmente decidí validar según el tipo de input que sea, para así pasarlos todos por un foreach y esta es mi función de validación:
Código PHP:
Ver original
  1. function t_em_theme_options_validate( $input ){
  2.     global $excerpt_options, $slider_layout;
  3.  
  4.     // All the checkbox are either 0 or 1
  5.     foreach ( array(
  6.         'header-featured-image',
  7.     ) as $checkbox ) :
  8.         if ( !isset( $input[$checkbox] ) )
  9.             $input[$checkbox] = null;
  10.         $input[$checkbox] = ( $input[$checkbox] == 1 ? 1 : 0 );
  11.     endforeach;
  12.  
  13.     // Validate all radio options
  14.     $radio_options = array(
  15.         'header-options'    => array (
  16.             'set'        => 'header-set',
  17.             'callback'    => t_em_header_options(),
  18.         ),
  19.         'slider-options'    => array (
  20.             'set'        => 'slider-thumbnail',
  21.             'callback'    => $slider_layout,
  22.         ),
  23.         'archive-options'    => array (
  24.             'set'        => 'archive-set',
  25.             'callback'    => t_em_archive_options(),
  26.         ),
  27.         'excerpt-options'    => array (
  28.             'set'        => 'excerpt-set',
  29.             'callback'    => $excerpt_options,
  30.         ),
  31.         'layout-options'    => array (
  32.             'set'        => 'layout-set',
  33.             'callback'    => t_em_layout_options(),
  34.         ),
  35.     );
  36.     foreach ( $radio_options as $radio ) :
  37.         if ( ! isset( $input[$radio['set']] ) )
  38.             $input[$radio['set']] = null;
  39.         if ( ! array_key_exists( $input[$radio['set']], $radio['callback'] ) )
  40.             $input[$radio['set']] = null;
  41.     endforeach;
  42.  
  43.     // Validate all int (input[type="number"]) options
  44.     foreach( array (
  45.         'slider-thumbnail-width',
  46.         'slider-thumbnail-height',
  47.         'slider-number',
  48.         'excerpt-thumbnail-width',
  49.         'excerpt-thumbnail-height',
  50.         'layout-width',
  51.     ) as $int ) :
  52.         $input[$int] = wp_filter_nohtml_kses( $input[$int] );
  53.     endforeach;
  54.  
  55.     // Validate all url (input[type="url"]) options
  56.     foreach ( array (
  57.         'twitter-set',
  58.         'facebook-set',
  59.         'googlepluss-set',
  60.         'rss-set',
  61.     ) as $url ) :
  62.         $input[$url] = esc_url_raw( $input[$url] );
  63.     endforeach;
  64.  
  65.     // Validate all select list options
  66.     $select_options = array ( // No pincha
  67.         'slider-cat'        => array (
  68.             'set'        => 'slider-category',
  69.             'callback'    => t_em_slider_callback(),
  70.         ),
  71.     );
  72.     foreach ( $select_options as $select ) :
  73.         if ( ! array_key_exists( $input[$select['set']], $select['callback'] ) )
  74.             $input[$select['set']] = null;
  75.     endforeach;
  76.  
  77.     return $input;
  78. }
  79. ?>

Ahora, $excerpt_options y $slider_layout son un par de variables que me retornan el array del slider-set y el excerpt-set, que a su vez pertenecen a las funciones que llamo como callback en t_em_archive_options() y t_em_header_options(), por ejemplo:
Código PHP:
Ver original
  1. function t_em_header_options(){
  2.     $header_options = array (
  3.         'no-header-image' => array (
  4.             'value' => 'no-header-image',
  5.             'label' => __( 'No header image', 't_em' ),
  6.             'extend' => '',
  7.         ),
  8.         'header-image' => array (
  9.             'value' => 'header-image',
  10.             'label' => __( 'Header image', 't_em' ),
  11.             'extend' => t_em_header_image_callback(),
  12.         ),
  13.         'slider' => array (
  14.             'value' => 'slider',
  15.             'label' => __( 'Slider', 't_em' ),
  16.             'extend' => t_em_slider_callback(),
  17.         ),
  18.     );
  19.  
  20.     return apply_filters( 't_em_header_options', $header_options );
  21. }
Y aquí la función callback:
Código PHP:
Ver original
  1. function t_em_slider_callback(){
  2.     global $slider_layout;
  3.     $slider_layout = array (
  4.         'slider-thumbnail-left' => array (
  5.             'value' => 'slider-thumbnail-left',
  6.             'label' => __( 'Slider thumbnail on left', 't_em' ),
  7.             'thumbnail' => T_EM_FUNCTIONS_DIR_IMG . '/slider-thumbnail-left.png',
  8.         ),
  9.         'slider-thumbnail-right' => array (
  10.             'value' => 'slider-thumbnail-right',
  11.             'label' => __( 'Slider thumbnail on right', 't_em' ),
  12.             'thumbnail' => T_EM_FUNCTIONS_DIR_IMG . '/slider-thumbnail-right.png',
  13.         ),
  14.         'slider-thumbnail-full' => array (
  15.             'value' => 'slider-thumbnail-full',
  16.             'label' => __( 'Slider thumbnail on full', 't_em' ),
  17.             'thumbnail' => T_EM_FUNCTIONS_DIR_IMG . '/slider-thumbnail-full.png',
  18.         ),
  19.     );
  20. // aquí más código
  21. }
Entonces, lo que me falta, como dije antes, es validar un select, de donde escojo una categoría determinada para mostrar en el slider del theme, pero creo tener claro qué debo hacer, es que me devuelva el valor mediante un array (como los anteriores), esto es lo que tengo:
Código PHP:
Ver original
  1. function t_em_slider_callback(){
  2. // Aquí hay más código
  3.     // Display a select list of categories
  4.     $list_categories = get_categories();
  5.     $extend_slider .= '<div class="sub-extend">';
  6.     $extend_slider .=    '<label class="description">';
  7.     $extend_slider .=         '<p>'. __( 'Select the category you want to be displayed in the slider section', 't_em' ) .'</p>';
  8.     $extend_slider .=         '<select name="t_em_theme_options[slider-category]">';
  9.     foreach ( $list_categories as $slider_category ) :
  10.         $selected_option = ( $options['slider-category'] == $slider_category->cat_ID ) ? 'selected="selected"' : '';
  11.         $extend_slider .=     '<option value="'.$slider_category->cat_ID.'" '.$selected_option.'>'.$slider_category->name.'</option>';
  12.     endforeach;
  13.     $extend_slider .=         '</select>';
  14.     $extend_slider .=    '</label>';
  15.     $extend_slider .= '</div>';
  16. }

En fin, va funcionando, en cuanto lo termine publico la solución completa...

Gracias.
__________________
Friki y Blogger por Cuenta Propia:213
Twenty'em: Theming is Prose

Etiquetas: settings-api, theme-options.php
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 23:54.