Skip to content

Instantly share code, notes, and snippets.

@brasofilo
Last active December 26, 2015 01:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brasofilo/7073558 to your computer and use it in GitHub Desktop.
Save brasofilo/7073558 to your computer and use it in GitHub Desktop.
dashboard-widget.md

#Widget de Escritorio con Callback Handle ###--WordPress Plugin--

Demonstración de como añadir un widget de escritorio configurable. Elije 3 páginas y serán mostradas en pestañas. Basado en el ejemplo del Codex y en el artículo Tabbed Meta Box In WordPress.

plugin.php

<?php
/**
 * Plugin Name: Dashboard Widget with Control Callback
 * Plugin URI:  https://gist.github.com/brasofilo/7073558
 * Description: Demonstración de como añadir un widget de escritório configurable. Elije 3 páginas y seran mostradas en pestañas.
 * Version:     1.0
 * Author:      Rodolfo Buaiz
 * Author URI:  http://brasofilo.com
 */

add_action(
	'plugins_loaded',
	array ( B5F_Dashboard_Widget_Configurable::get_instance(), 'plugin_setup' )
);

class B5F_Dashboard_Widget_Configurable
{
	protected static $instance = NULL;
	public $plugin_url = NULL;
    private $option_name = 'b5f_dashboard_widget_options';
	
	public function __construct() {}

    public static function get_instance()
	{
		NULL === self::$instance and self::$instance = new self;
		return self::$instance;
	}

    /**
     * Iniciar plugin
     */
	public function plugin_setup()
	{
		$this->plugin_url    = plugins_url( '/', __FILE__ );
        add_action( 'wp_dashboard_setup', array( $this, 'add_widget' ) );
        add_action( 'admin_print_styles-index.php', array( $this, 'enqueue' ) );
	}
	
    /**
     * Añadir widget al escritorio
     */
    public function add_widget()
    {
        wp_add_dashboard_widget(
            'b5f_dashboard_widget', 
            __( 'Dashboard Widget con Control Callback' ), 
            array( $this, 'print_widget' ), 
            array( $this, 'config_widget' )
        );
    }
    
    /** 
     * Hojas de estilo y JavaScript
     */
    public function enqueue()
    {
        $color = get_user_meta( get_current_user_id(), 'admin_color', true );
        wp_enqueue_style(  
            'jf-metabox-tabs', 
            $this->plugin_url . 'metabox-tabs.css' 
        );
        wp_enqueue_style(  
            "jf-$color",       
            $this->plugin_url . "metabox-$color.css"
        );
        wp_enqueue_script( 
            'jf-metabox-tabs', 
            $this->plugin_url . 'metabox-tabs.js', 
            array( 'jquery' ) 
        );
    }
    
    /**
     * Imprimir el contenido del widget
     */
    public function print_widget()
    {
        # datos guardados
        if( !$widget_options = get_option( $this->option_name ) )
            $widget_options = array( );

        # opciones por defecto
        $output = sprintf(
            '<h2 style="text-align:right">%s</h2>',
            __( 'Por favor, configura el widget &#x261D;' )
        );

        # confirmar que los datos guardados tienen contenidos
        $saved_tab_1 = isset( $widget_options['tab_1'] ) 
            ? $widget_options['tab_1'] : false;
        $saved_tab_2 = isset( $widget_options['tab_2'] ) 
            ? $widget_options['tab_2'] : false;
        $saved_tab_3 = isset( $widget_options['tab_3'] ) 
            ? $widget_options['tab_3'] : false;

        # todas las pestañas ajustadas, ahora si, imprime contenidos
        if( $saved_tab_1 && $saved_tab_2 && $saved_tab_3 )
        {
            $post1 = get_post( $saved_tab_1 );
            $post2 = get_post( $saved_tab_2 );
            $post3 = get_post( $saved_tab_3 );
            $data = array(
                'p1' => array( 
                    $post1->post_title, 
                    do_shortcode( html_entity_decode( $post1->post_content ) ) 
                ),
                'p2' => array( 
                    $post2->post_title, 
                    do_shortcode( html_entity_decode( $post2->post_content ) ) 
                ),
                'p3' => array( 
                    $post3->post_title, 
                    do_shortcode( html_entity_decode( $post3->post_content ) ) 
                ),
            );
            $output = $this->sample_meta_box( $data );
        }
        echo "<div class='feature_post_class_wrap mi-hide' id='feature_post_wrap'>
            $output
        </div>
        ";
        # esconder algunos divs si JavaScript no esta habilitado
        echo '<script>
               document.getElementById("feature_post_wrap").className = document.getElementById("feature_post_wrap").className.replace("mi-hide","hide");
               document.getElementsByTagName("h3").className = document.getElementsByTagName("h3").className.replace("mi-hide","hide");
</script>'; 
    }

    /**
     * Guardar los datos de configuración del widget
     */
    public function config_widget()
    {
        # datos guardados
        if( !$widget_options = get_option( $this->option_name ) )
            $widget_options = array( );

        # procesar datos enviados
        if( 'POST' == $_SERVER['REQUEST_METHOD'] && isset( $_POST[$this->option_name] ) )
        {
            # minor validation
            $widget_options['tab_1'] = absint( $_POST[$this->option_name]['tab_1'] );
            $widget_options['tab_2'] = absint( $_POST[$this->option_name]['tab_2'] );
            $widget_options['tab_3'] = absint( $_POST[$this->option_name]['tab_3'] );
            # save update
            update_option( $this->option_name, $widget_options );
        }

        # valores por defecto
        if( !isset( $widget_options['tab_1'] ) )
            $widget_options['tab_1'] = '';
        if( !isset( $widget_options['tab_2'] ) )
            $widget_options['tab_2'] = '';
        if( !isset( $widget_options['tab_3'] ) )
            $widget_options['tab_3'] = '';

        # imprimir selectores de páginas
        echo "<p><strong>Select pages for tabs</strong></p>";
        $this->print_drop_down( $widget_options, 'Tab 1', 'tab_1' );
        $this->print_drop_down( $widget_options, 'Tab 2', 'tab_2' );
        $this->print_drop_down( $widget_options, 'Tab 3', 'tab_3' );
    }
    
    /**
     * Generar selectores de paginas
     * 
     * @param array   $widget_options
     * @param string  $title
     * @param integer $id
     */
    private function print_drop_down( $widget_options, $title, $id )
    {
        echo "<div class='feature_post_class_wrap' style='margin-bottom:4px;padding:2px;border-left: 6px solid #ECECEC;'>
            <label style='margin-right:20px'>$title</label> ";
        wp_dropdown_pages( array(
            'post_type'        => 'page',
            'selected'         => $widget_options[$id],
            'name'             => "{$this->option_name}[$id]",
            'id'               => $id,
            'show_option_none' => __( '- Select -' )
        ) );
        echo "</div>";
    }
    
    /**
     * Imprimir las pestañas y sus contenidos
     * @param object $data
     * @return string
     */
    private function sample_meta_box( $data )
    {
        $return = <<<HTML
        <div class="metabox-tabs-div">
            <ul class="metabox-tabs mi-hide" id="metabox-tabs">
                <li class="active tab1"><a class="active" href="javascript:void(null);">
                    {$data['p1'][0]}
                </a></li>
                <li class="tab2"><a href="javascript:void(null);">
                    {$data['p2'][0]}
                </a></li>
                <li class="tab3"><a href="javascript:void(null);">
                    {$data['p3'][0]}
                </a></li>
            </ul>
            <div class="tab1">
                <h3 class=mi-hide>{$data['p1'][0]}</h3>
                {$data['p1'][1]}
            </div>
            <div class="tab2">
                {$data['p2'][1]}
                </table>
            </div>
            <div class="tab3">
                {$data['p3'][1]}
            </div>
        </div>
HTML;
        return $return;
    }
}

metabox-tabs.js

jQuery(document).ready(function($) 
{
    /* mostrar contenidos (estan ocultos por CSS, si JS esta activo */
    $('.feature_post_class_wrap.hide').show('slow');
    
    /* botones de pestaña */
    $('.metabox-tabs li a').each(function(i) 
    {
        var thisTab = $(this).parent().attr('class').replace(/active /, '');

        if ('active' != $(this).attr('class'))
            $('div.' + thisTab).hide();

        $('div.' + thisTab).addClass('tab-content');
        
        /* cambiar pestañas */
        $(this).click(function() 
        {
            if( $(this).parent().hasClass('active') )
                return;
            // esconder contenido hijo
            $(this).parent().parent().parent().children('div').hide('fast');

            // desactivar todas pestañas
            $(this).parent().parent('ul').find('li.active').removeClass('active');

            // activar pestaña elejida
            $(this).parent().parent().parent().find('div.' + thisTab).show('fast');
            $(this).parent().parent().parent().find('li.' + thisTab).addClass('active');
        });
    });
});

metabox-tabs.css

/**
 * Metabox Tabs
 */
ul.metabox-tabs {
    margin-top: 12px;
    margin-bottom: 3px;
}
.metabox-tabs-div ul {
    list-style: none;
}
.metabox-tabs li {
    display: inline;
}
ul.metabox-tabs li.active {
    border-style: solid solid none;
    border-width: 1px 1px 0;
}
ul.metabox-tabs li {
    padding: 5px;
    -moz-border-radius: 3px 3px 0 0;
    -webkit-border-top-left-radius: 3px;
    -webkit-border-top-right-radius: 3px;
    -khtml-border-top-left-radius: 3px;
    -khtml-border-top-right-radius: 3px;
    border-top-left-radius: 3px;
    border-top-right-radius: 3px;
    font-size: 1.2em;
    font-weight: bold;
    letter-spacing: .1em;
}
.metabox-tabs a {
    text-decoration: none;
}
.metabox-tabs-div div.tabs-panel {
    overflow: auto;
    padding: 0.5em 0.9em;
    border-style: solid;
    border-width: 1px;
}
.tab-content{
    overflow: auto;
    padding: 0.5em 0.9em;
    border-style: solid;
    border-width: 1px;
}
.feature_post_class_wrap.hide {
    display:none
}

metabox-classic.css

/**
 * Metabox Tabs
 */
    ul.metabox-tabs li.active {
    background-color: #EFF8FF;
}
    ul.metabox-tabs li.active, div.tab-content {
    border-color: #D1E5EE;
}
.metabox-tabs .active a {
    color: #333;
}

metabox-fresh.css

/**
 * Metabox Tabs
 */
ul.metabox-tabs li.active {
    background-color: #F1F1F1;
}
ul.metabox-tabs li.active, div.tab-content {
    border-color: #DFDFDF;
}
.metabox-tabs .active a {
    color: #333;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment