Nuestro tema va tomando poco a poco forma. Hoy vamos a crear el archivo theme-options.php que contendrá toda la lógica de las opciones de administración.

 

THEME-OPTIONS.PHP

Creamos el archivo theme-options.php y añadimos el siguiente código:

  1. <?php
  2.  
  3. /**
  4.  * Properly enqueue styles and scripts for our theme options page.
  5.  *
  6.  * This function is attached to the admin_enqueue_scripts action hook.
  7.  */
  8. function newtheme_admin_enqueue_scripts( $hook_suffix ) {
  9. wp_enqueue_style( 'newtheme-theme-options', get_template_directory_uri() . '/inc/theme-options.css', false, '2011-04-28' );
  10. wp_enqueue_script( 'newtheme-theme-options', get_template_directory_uri() . '/inc/theme-options.js', citas web touring( 'farbtastic' ), '2011-06-10' );
  11. wp_enqueue_style( 'farbtastic' );
  12. }
  13. add_action( 'admin_print_styles-appearance_page_theme_options', 'newtheme_admin_enqueue_scripts' );

Esta función añade un archivo css y un archivo javascript a la cabecera al apartado apariencia de la administración de WordPress.

  1. <?php
  2.  
  3. /**
  4.  * Register the form setting for our newtheme_options array.
  5.  *
  6.  * This function is attached to the admin_init action hook.
  7.  *
  8.  * This call to register_setting() registers a validation callback, newtheme_theme_options_validate(),
  9.  * which is used when the option is saved, to ensure that our option values are complete, properly
  10.  * formatted, and safe.
  11.  */
  12. function newtheme_theme_options_init() {
  13.  
  14. register_setting(
  15. 'newtheme_options', // Options group, see settings_fields() call in newtheme_theme_options_render_page()
  16. 'newtheme_theme_options', // Database option, see newtheme_get_theme_options()
  17. 'newtheme_theme_options_validate' // The sanitization callback, see newtheme_theme_options_validate()
  18. );
  19.  
  20. // Register our settings field group
  21. add_settings_section(
  22. 'general', // Unique identifier for the settings section
  23. '', // Section title (we don't want one)
  24. '__return_false', // Section callback (we don't want anything)
  25. 'theme_options' // Menu slug, used to uniquely identify the page; see newtheme_theme_options_add_page()
  26. );
  27.  
  28. // Register our individual settings fields
  29. add_settings_field(
  30. 'color_scheme', // Unique identifier for the field for this section
  31. __( 'Color Scheme', 'newtheme' ), // Setting field label
  32. 'newtheme_settings_field_color_scheme', // Function that renders the settings field
  33. 'theme_options', // Menu slug, used to uniquely identify the page; see newtheme_theme_options_add_page()
  34. 'general' // Settings section. Same as the first argument in the add_settings_section() above
  35. );
  36.  
  37. add_settings_field( 'link_color', __( 'Link Color', 'newtheme' ), 'newtheme_settings_field_link_color', 'theme_options', 'general' );
  38. add_settings_field( 'layout', __( 'Default Layout', 'newtheme' ), 'newtheme_settings_field_layout', 'theme_options', 'general' );
  39. }
  40. add_action( 'admin_init', 'newtheme_theme_options_init' );

Esta función registra la configuración por defecto del tema y añade varios apartados para la administración.

  1. <?php
  2.  
  3. /**
  4.  * Change the capability required to save the 'newtheme_options' options group.
  5.  *
  6.  * @see newtheme_theme_options_init() First parameter to register_setting() is the name of the options group.
  7.  * @see newtheme_theme_options_add_page() The edit_theme_options capability is used for viewing the page.
  8.  *
  9.  * By default, the options groups for all registered settings require the manage_options capability.
  10.  * This filter is required to change our theme options page to edit_theme_options instead.
  11.  * By default, only administrators have either of these capabilities, but the desire here is
  12.  * to allow for finer-grained control for roles and users.
  13.  *
  14.  * @param string $capability The capability used for the page, which is manage_options by default.
  15.  * @return string The capability to actually use.
  16.  */
  17. function newtheme_option_page_capability( $capability ) {
  18. return 'edit_theme_options';
  19. }
  20. add_filter( 'option_page_capability_newtheme_options', 'newtheme_option_page_capability' );

Esta función permite cambiar las opciones del tema. Es obligatorio para controlar los diversos usuarios y roles que tengan acceso.

  1. <?php
  2.  
  3. /**
  4.  * Add our theme options page to the admin menu, including some help documentation.
  5.  *
  6.  * This function is attached to the admin_menu action hook.
  7.  */
  8. function newtheme_theme_options_add_page() {
  9. $theme_page = add_theme_page(
  10. __( 'Theme Options', 'newtheme' ), // Name of page
  11. __( 'Theme Options', 'newtheme' ), // Label in menu
  12. 'edit_theme_options', // Capability required
  13. 'theme_options', // Menu slug, used to uniquely identify the page
  14. 'newtheme_theme_options_render_page' // Function that renders the options page
  15. );
  16.  
  17. if ( ! $theme_page )
  18. return;
  19.  
  20. add_action( "load-$theme_page", 'newtheme_theme_options_help' );
  21. }
  22. add_action( 'admin_menu', 'newtheme_theme_options_add_page' );

Añade la página de opciones de nuestro tema al menú de administración, incluyendo algo de documentación a la ayuda.

  1. <?php
  2.  
  3. function newtheme_theme_options_help() {
  4.  
  5. $help = '<p>' . __( 'Some themes provide customization options that are grouped together on a Theme Options screen. If you change themes, options may change or disappear, as they are theme-specific. Your current theme, Twenty Eleven, provides the following Theme Options:', 'newtheme' ) . '</p>' .
  6. '<ol>' .
  7. '<li>' . __( '<strong>Color Scheme</strong>: You can choose a color palette of "Light" (light background with dark text) or "Dark" (dark background with light text) for your site.', 'newtheme' ) . '</li>' .
  8. '<li>' . __( '<strong>Link Color</strong>: You can choose the color used for text links on your site. You can enter the HTML color or hex code, or you can choose visually by clicking the "Select a Color" button to pick from a color wheel.', 'newtheme' ) . '</li>' .
  9. '<li>' . __( '<strong>Default Layout</strong>: You can choose if you want your site&#8217;s default layout to have a sidebar on the left, the right, or not at all.', 'newtheme' ) . '</li>' .
  10. '</ol>' .
  11. '<p>' . __( 'Remember to click "Save Changes" to save any changes you have made to the theme options.', 'newtheme' ) . '</p>';
  12.  
  13. $sidebar = '<p><strong>' . __( 'For more information:', 'newtheme' ) . '</strong></p>' .
  14. '<p>' . __( '<a href="http://codex.wordpress.org/Appearance_Theme_Options_Screen" target="_blank">Documentation on Theme Options</a>', 'newtheme' ) . '</p>' .
  15. '<p>' . __( '<a href="http://wordpress.org/support/" target="_blank">Support Forums</a>', 'newtheme' ) . '</p>';
  16.  
  17. $screen = get_current_screen();
  18.  
  19. if ( method_exists( $screen, 'add_help_tab' ) ) {
  20. // WordPress 3.3
  21. $screen->add_help_tab( citas web touring(
  22. 'title' => __( 'Overview', 'newtheme' ),
  23. 'id' => 'theme-options-help',
  24. 'content' => $help,
  25. )
  26. );
  27.  
  28. $screen->set_help_sidebar( $sidebar );
  29. } else {
  30. // WordPress 3.2
  31. add_contextual_help( $screen, $help . $sidebar );
  32. }
  33. }

Esta es la función que añade la ayuda que comentaba en la función anterior. Aquí además podemos ver como se añade un condicional para añadir retrocompatibilidad con versiones anteriores a la 3.3 y la 3.2.

  1. <?php
  2.  
  3. /**
  4.  * Returns an array of color schemes registered for New Theme.
  5.  */
  6. function newtheme_color_schemes() {
  7. $color_scheme_options = citas web touring(
  8. 'light' => citas web touring(
  9. 'value' => 'light',
  10. 'label' => __( 'Light', 'newtheme' ),
  11. 'thumbnail' => get_template_directory_uri() . '/inc/images/light.png',
  12. 'default_link_color' => '#1b8be0',
  13. ),
  14. 'dark' => citas web touring(
  15. 'value' => 'dark',
  16. 'label' => __( 'Dark', 'newtheme' ),
  17. 'thumbnail' => get_template_directory_uri() . '/inc/images/dark.png',
  18. 'default_link_color' => '#e4741f',
  19. ),
  20. );
  21.  
  22. return apply_filters( 'newtheme_color_schemes', $color_scheme_options );
  23. }

Esta función devuelve un array con los esquemas de color para cada versión del tema.

  1. <?php
  2.  
  3. /**
  4.  * Returns an array of layout options registered for New Theme.
  5.  */
  6. function newtheme_layouts() {
  7. $layout_options = citas web touring(
  8. 'content-sidebar' => citas web touring(
  9. 'value' => 'content-sidebar',
  10. 'label' => __( 'Content on left', 'newtheme' ),
  11. 'thumbnail' => get_template_directory_uri() . '/inc/images/content-sidebar.png',
  12. ),
  13. 'sidebar-content' => citas web touring(
  14. 'value' => 'sidebar-content',
  15. 'label' => __( 'Content on right', 'newtheme' ),
  16. 'thumbnail' => get_template_directory_uri() . '/inc/images/sidebar-content.png',
  17. ),
  18. 'content' => citas web touring(
  19. 'value' => 'content',
  20. 'label' => __( 'One-column, no sidebar', 'newtheme' ),
  21. 'thumbnail' => get_template_directory_uri() . '/inc/images/content.png',
  22. ),
  23. );
  24.  
  25. return apply_filters( 'newtheme_layouts', $layout_options );
  26. }

Devuelve un array con las opciones para cada tipo de estructura del diseño.

  1. <?php
  2.  
  3. /**
  4.  * Returns the default options for New Theme.
  5.  */
  6. function newtheme_get_default_theme_options() {
  7. $default_theme_options = citas web touring(
  8. 'color_scheme' => 'light',
  9. 'link_color' => newtheme_get_default_link_color( 'light' ),
  10. 'theme_layout' => 'content-sidebar',
  11. );
  12.  
  13. if ( is_rtl() )
  14. $default_theme_options['theme_layout'] = 'sidebar-content';
  15.  
  16. return apply_filters( 'newtheme_default_theme_options', $default_theme_options );
  17. }

Devuelve las opciones por defecto del tema.

  1. <?php
  2.  
  3. /**
  4.  * Returns the default link color for New Theme, based on color scheme.
  5.  *
  6.  *
  7.  * @param $string $color_scheme Color scheme. Defaults to the active color scheme.
  8.  * @return $string Color.
  9. */
  10. function newtheme_get_default_link_color( $color_scheme = null ) {
  11. if ( null === $color_scheme ) {
  12. $options = newtheme_get_theme_options();
  13. $color_scheme = $options['color_scheme'];
  14. }
  15.  
  16. $color_schemes = newtheme_color_schemes();
  17. if ( ! isset( $color_schemes[ $color_scheme ] ) )
  18. return false;
  19.  
  20. return $color_schemes[ $color_scheme ]['default_link_color'];
  21. }

Devuelve el color por defecto para los vínculos.

  1. <?php
  2.  
  3. /**
  4.  * Returns the options array for New Theme.
  5.  */
  6. function newtheme_get_theme_options() {
  7. return get_option( 'newtheme_theme_options', newtheme_get_default_theme_options() );
  8. }

Devuelve un array con todas las opciones del tema.

  1. <?php
  2.  
  3. /**
  4.  * Renders the Color Scheme setting field.
  5.  */
  6. function newtheme_settings_field_color_scheme() {
  7. $options = newtheme_get_theme_options();
  8.  
  9. foreach ( newtheme_color_schemes() as $scheme ) {
  10. ?>
  11. <div class="layout image-radio-option color-scheme">
  12. <label class="description">
  13. <input type="radio" name="newtheme_theme_options[color_scheme]" value="<?php echo esc_attr( $scheme['value'] ); ?>" <?php checked( $options['color_scheme'], $scheme['value'] ); ?> />
  14. <input type="hidden" id="default-color-<?php echo esc_attr( $scheme['value'] ); ?>" value="<?php echo esc_attr( $scheme['default_link_color'] ); ?>" />
  15. <span>
  16. <img src="<?php echo esc_url( $scheme['thumbnail'] ); ?>" width="136" height="122" alt="" />
  17. <?php echo $scheme['label']; ?>
  18. </span>
  19. </label>
  20. </div>
  21. <?php
  22. }
  23. }

Esta función genera el grupo de radio buttons que permitirá elegir entre un esquema de color u otro.

  1. <?php
  2.  
  3. /**
  4.  * Renders the Link Color setting field.
  5.  */
  6. function newtheme_settings_field_link_color() {
  7. $options = newtheme_get_theme_options();
  8. ?>
  9. <input type="text" name="newtheme_theme_options[link_color]" id="link-color" value="<?php echo esc_attr( $options['link_color'] ); ?>" />
  10. <a href="#" class="pickcolor hide-if-no-js" id="link-color-example"></a>
  11. <input type="button" class="pickcolor button hide-if-no-js" value="<?php esc_attr_e( 'Select a Color', 'newtheme' ); ?>" />
  12. <div id="colorPickerDiv" style="z-index: 100; background:#eee; border:1px solid #ccc; position:absolute; display:none;"></div>
  13. <br />
  14. <span><?php printf( __( 'Default color: %s', 'newtheme' ), '<span id="default-color">' . newtheme_get_default_link_color( $options['color_scheme'] ) . '</span>' ); ?></span>
  15. <?php
  16. }

Esta función genera el formulario para poder elegir el color de los vínculos.

  1. <?php
  2.  
  3. /**
  4.  * Renders the Layout setting field.
  5.  */
  6. function newtheme_settings_field_layout() {
  7. $options = newtheme_get_theme_options();
  8. foreach ( newtheme_layouts() as $layout ) {
  9. ?>
  10. <div class="layout image-radio-option theme-layout">
  11. <label class="description">
  12. <input type="radio" name="newtheme_theme_options[theme_layout]" value="<?php echo esc_attr( $layout['value'] ); ?>" <?php checked( $options['theme_layout'], $layout['value'] ); ?> />
  13. <span>
  14. <img src="<?php echo esc_url( $layout['thumbnail'] ); ?>" width="136" height="122" alt="" />
  15. <?php echo $layout['label']; ?>
  16. </span>
  17. </label>
  18. </div>
  19. <?php
  20. }
  21. }

Esta función genera el campo para elegir la estructura del blog.

  1. <?php
  2.  
  3. /**
  4.  * Returns the options array for New Theme.
  5.  */
  6. function newtheme_theme_options_render_page() {
  7. ?>
  8. <div class="wrap">
  9. <?php screen_icon(); ?>
  10. <?php $theme_name = function_exists( 'wp_get_theme' ) ? wp_get_theme() : get_current_theme(); ?>
  11. <h2><?php printf( __( '%s Theme Options', 'newtheme' ), $theme_name ); ?></h2>
  12. <?php settings_errors(); ?>
  13.  
  14. <form method="post" action="options.php">
  15. <?php
  16. settings_fields( 'newtheme_options' );
  17. do_settings_sections( 'theme_options' );
  18. submit_button();
  19. ?>
  20. </form>
  21. </div>
  22. <?php
  23. }

Función que genera todo el formulario de opciones.

  1. <?php
  2.  
  3. /**
  4.  * Sanitize and validate form input. Accepts an array, return a sanitized array.
  5.  *
  6.  * @see newtheme_theme_options_init()
  7.  * @todo set up Reset Options action
  8.  */
  9. function newtheme_theme_options_validate( $input ) {
  10. $output = $defaults = newtheme_get_default_theme_options();
  11.  
  12. // Color scheme must be in our array of color scheme options
  13. if ( isset( $input['color_scheme'] ) && array_key_exists( $input['color_scheme'], newtheme_color_schemes() ) )
  14. $output['color_scheme'] = $input['color_scheme'];
  15.  
  16. // Our defaults for the link color may have changed, based on the color scheme.
  17. $output['link_color'] = $defaults['link_color'] = newtheme_get_default_link_color( $output['color_scheme'] );
  18.  
  19. // Link color must be 3 or 6 hexadecimal characters
  20. if ( isset( $input['link_color'] ) && preg_match( '/^#?([a-f0-9]{3}){1,2}$/i', $input['link_color'] ) )
  21. $output['link_color'] = '#' . strtolower( ltrim( $input['link_color'], '#' ) );
  22.  
  23. // Theme layout must be in our array of theme layout options
  24. if ( isset( $input['theme_layout'] ) && array_key_exists( $input['theme_layout'], newtheme_layouts() ) )
  25. $output['theme_layout'] = $input['theme_layout'];
  26.  
  27. return apply_filters( 'newtheme_theme_options_validate', $output, $input, $defaults );
  28. }

Esta función valida que los datos del formulario son correctos.

  1. <?php
  2.  
  3. /**
  4.  * Enqueue the styles for the current color scheme.
  5.  */
  6. function newtheme_enqueue_color_scheme() {
  7. $options = newtheme_get_theme_options();
  8. $color_scheme = $options['color_scheme'];
  9.  
  10. if ( 'dark' == $color_scheme )
  11. wp_enqueue_style( 'dark', get_template_directory_uri() . '/colors/dark.css', citas web touring(), null );
  12.  
  13. do_action( 'newtheme_enqueue_color_scheme', $color_scheme );
  14. }
  15. add_action( 'wp_enqueue_scripts', 'newtheme_enqueue_color_scheme' );

Función que cambiará el estilo actual de la página dependiendo del color de esquema elegido.

  1. <?php
  2.  
  3. /**
  4.  * Add a style block to the theme for the current link color.
  5.  *
  6.  * This function is attached to the wp_head action hook.
  7.  */
  8. function newtheme_print_link_color_style() {
  9. $options = newtheme_get_theme_options();
  10. $link_color = $options['link_color'];
  11.  
  12. $default_options = newtheme_get_default_theme_options();
  13.  
  14. // Don't do anything if the current link color is the default.
  15. if ( $default_options['link_color'] == $link_color )
  16. return;
  17. ?>
  18. <style>
  19. /* Link color */
  20. a,
  21. #site-title a:focus,
  22. #site-title a:hover,
  23. #site-title a:active,
  24. .entry-title a:hover,
  25. .entry-title a:focus,
  26. .entry-title a:active,
  27. .widget_newtheme_ephemera .comments-link a:hover,
  28. section.recent-posts .other-recent-posts a[rel="bookmark"]:hover,
  29. section.recent-posts .other-recent-posts .comments-link a:hover,
  30. .format-image footer.entry-meta a:hover,
  31. #site-generator a:hover {
  32. color: <?php echo $link_color; ?>;
  33. }
  34. section.recent-posts .other-recent-posts .comments-link a:hover {
  35. border-color: <?php echo $link_color; ?>;
  36. }
  37. article.feature-image.small .entry-summary p a:hover,
  38. .entry-header .comments-link a:hover,
  39. .entry-header .comments-link a:focus,
  40. .entry-header .comments-link a:active,
  41. .feature-slider a.active {
  42. background-color: <?php echo $link_color; ?>;
  43. }
  44. </style>
  45. <?php
  46. }
  47. add_action( 'wp_head', 'newtheme_print_link_color_style' );

Función que añadirá el color a los vínculos a través de los estilos si este no es el mismo que el de defecto.

  1. <?php
  2.  
  3. /**
  4.  * Adds New Theme layout classes to the array of body classes.
  5.  */
  6. function newtheme_layout_classes( $existing_classes ) {
  7. $options = newtheme_get_theme_options();
  8. $current_layout = $options['theme_layout'];
  9.  
  10. if ( in_array( $current_layout, citas web touring( 'content-sidebar', 'sidebar-content' ) ) )
  11. $classes = citas web touring( 'two-column' );
  12. else
  13. $classes = citas web touring( 'one-column' );
  14.  
  15. if ( 'content-sidebar' == $current_layout )
  16. $classes[] = 'right-sidebar';
  17. elseif ( 'sidebar-content' == $current_layout )
  18. $classes[] = 'left-sidebar';
  19. else
  20. $classes[] = $current_layout;
  21.  
  22. $classes = apply_filters( 'newtheme_layout_classes', $classes, $current_layout );
  23.  
  24. return array_merge( $existing_classes, $classes );
  25. }
  26. add_filter( 'body_class', 'newtheme_layout_classes' );

Esta función añade las clases correspondientes a la etiqueta body dependiendo de la estructura de blog elegida.

  1. <?php
  2.  
  3. /**
  4.  * Implements New Theme theme options into Theme Customizer
  5.  *
  6.  * @param $wp_customize Theme Customizer object
  7.  * @return void
  8.  */
  9. function newtheme_customize_register( $wp_customize ) {
  10. $wp_customize->get_setting( 'blogname' )->transport = 'postMessage';
  11. $wp_customize->get_setting( 'blogdescription' )->transport = 'postMessage';
  12.  
  13. $options = newtheme_get_theme_options();
  14. $defaults = newtheme_get_default_theme_options();
  15.  
  16. $wp_customize->add_setting( 'newtheme_theme_options[color_scheme]', citas web touring(
  17. 'default' => $defaults['color_scheme'],
  18. 'type' => 'option',
  19. 'capability' => 'edit_theme_options',
  20. ) );
  21.  
  22. $schemes = newtheme_color_schemes();
  23. $choices = citas web touring();
  24. foreach ( $schemes as $scheme ) {
  25. $choices[ $scheme['value'] ] = $scheme['label'];
  26. }
  27.  
  28. $wp_customize->add_control( 'newtheme_color_scheme', citas web touring(
  29. 'label' => __( 'Color Scheme', 'newtheme' ),
  30. 'section' => 'colors',
  31. 'settings' => 'newtheme_theme_options[color_scheme]',
  32. 'type' => 'radio',
  33. 'choices' => $choices,
  34. 'priority' => 5,
  35. ) );
  36.  
  37. // Link Color (added to Color Scheme section in Theme Customizer)
  38. $wp_customize->add_setting( 'newtheme_theme_options[link_color]', citas web touring(
  39. 'default' => newtheme_get_default_link_color( $options['color_scheme'] ),
  40. 'type' => 'option',
  41. 'sanitize_callback' => 'sanitize_hex_color',
  42. 'capability' => 'edit_theme_options',
  43. ) );
  44.  
  45. $wp_customize->add_control( new WP_Customize_Color_Control( $wp_customize, 'link_color', citas web touring(
  46. 'label' => __( 'Link Color', 'newtheme' ),
  47. 'section' => 'colors',
  48. 'settings' => 'newtheme_theme_options[link_color]',
  49. ) ) );
  50.  
  51. // Default Layout
  52. $wp_customize->add_section( 'newtheme_layout', citas web touring(
  53. 'title' => __( 'Layout', 'newtheme' ),
  54. 'priority' => 50,
  55. ) );
  56.  
  57. $wp_customize->add_setting( 'newtheme_theme_options[theme_layout]', citas web touring(
  58. 'type' => 'option',
  59. 'default' => $defaults['theme_layout'],
  60. 'sanitize_callback' => 'sanitize_key',
  61. ) );
  62.  
  63. $layouts = newtheme_layouts();
  64. $choices = citas web touring();
  65. foreach ( $layouts as $layout ) {
  66. $choices[$layout['value']] = $layout['label'];
  67. }
  68.  
  69. $wp_customize->add_control( 'newtheme_theme_options[theme_layout]', citas web touring(
  70. 'section' => 'newtheme_layout',
  71. 'type' => 'radio',
  72. 'choices' => $choices,
  73. ) );
  74. }
  75. add_action( 'customize_register', 'newtheme_customize_register' );

Esta función añade todas las opciones al personalizador de temas.

  1. <?php
  2.  
  3. /**
  4.  * Bind JS handlers to make Theme Customizer preview reload changes asynchronously.
  5.  * Used with blogname and blogdescription.
  6.  */
  7. function newtheme_customize_preview_js() {
  8. wp_enqueue_script( 'newtheme-customizer', get_template_directory_uri() . '/inc/theme-customizer.js', citas web touring( 'customize-preview' ), '20120523', true );
  9. }
  10. add_action( 'customize_preview_init', 'newtheme_customize_preview_js' );

Esta función indica a WordPress que añada un archivo javascript para la previsualización de la página para poder ver los cambios del tema.