Limitar el número de widgets en las barras laterales

15

Si utilizo un área personalizada de widgets (por ejemplo, un pie de página) donde solo hay un número limitado de espacios para los widgets (por diseño), ¿puedo limitar la cantidad de widgets que el usuario puede incluir en esa área específica de widgets? No importa si la solución está en el backend o en el extremo frontal. Gracias.

    
pregunta Jukov 13.06.2011 - 21:51

4 respuestas

10

Resolví esto en Javascript. Si quieres evitarlo por completo, también deberías hacerlo desde el lado del servidor, ya que puedes editar los widgets con Javascript desactivado (¡pruébalo!).

Las diferentes barras laterales se verifican cuando coloca los widgets en ellos o se aleja de ellos. Si se llenan, el color de fondo cambia y ya no puede colocar elementos en ellos. Si, en el inicio, la barra lateral ya está más que llena (porque ajustó la restricción), el color de fondo se vuelve rojo. Aún puedes arrastrar los widgets lejos de los widgets completos para hacerlos vacíos nuevamente.

Pruebeestecódigoparaencontrarformasdeagregaroeliminarwidgetsquenoencontré.La"magia" en el código jQuery proviene de Aman , quien respondió a una pregunta de desbordamiento de pila que publiqué al respecto .

Javascript:

jQuery( function( $ ) {
    var sidebarLimits = {
        'sidebar-1': 2,
        'sidebar-2': 2,
    };
    var realSidebars = $( '#widgets-right div.widgets-sortables' );
    var availableWidgets = $( '#widget-list' ).children( '.widget' );

    var checkLength = function( sidebar, delta ) {
        var sidebarId = sidebar.id;
        if ( undefined === sidebarLimits[sidebarId] ) {
            return;
        }

        // This is a limited sidebar
        // Find out how many widgets it already has
        var widgets = $( sidebar ).sortable( 'toArray' );
        $( sidebar ).toggleClass( 'sidebar-full', sidebarLimits[sidebarId] <= widgets.length + (delta || 0) );
        $( sidebar ).toggleClass( 'sidebar-morethanfull', sidebarLimits[sidebarId] < widgets.length + (delta || 0) );

        var notFullSidebars = $( 'div.widgets-sortables' ).not( '.sidebar-full' );
        availableWidgets.draggable( 'option', 'connectToSortable', notFullSidebars );
        realSidebars.sortable( 'option', 'connectWith', notFullSidebars );
    }

    // Check existing sidebars on startup
    realSidebars.map( function() {
        checkLength( this );
    } );

    // Update when dragging to this (sort-receive)
    // and away to another sortable (sort-remove)
    realSidebars.bind( 'sortreceive sortremove', function( event, ui ) {
        checkLength( this );
    } );

    // Update when dragging back to the "Available widgets" stack
    realSidebars.bind( 'sortstop', function( event, ui ) {
        if ( ui.item.hasClass( 'deleting' ) ) {
            checkLength( this, -1 );
        }
    } );

    // Update when the "Delete" link is clicked
    $( 'a.widget-control-remove' ).live( 'click', function() {
        checkLength( $( this ).closest( 'div.widgets-sortables' )[0], -1 );
    } );
} );

CSS:

.sidebar-full
{
    background-color: #cfe1ef !important;
}

.sidebar-morethanfull
{
    background-color: #c43 !important;
}

PHP para cargarlos:

$wpse19907_file = $plugin;
add_action( 'admin_enqueue_scripts', 'wpse19907_admin_enqueue_scripts' );
function wpse19907_admin_enqueue_scripts( $hook_suffix )
{
    if ( 'widgets.php' == $hook_suffix ) {
        wp_enqueue_script( 'wpse-19907', plugins_url( 'wpse-19907.js', $GLOBALS['wpse19907_file'] ), array(), false, true );
        wp_enqueue_style( 'wpse-19907', plugins_url( 'wpse-19907.css', $GLOBALS['wpse19907_file'] ) );
    }
}

Un intento de verificación del lado del servidor (probablemente aún no esté completo):

$wpse19907_sidebars_max_widgets = array(
    'sidebar-1' => 2,
);

add_action( 'sidebar_admin_setup', 'wpse19907_sidebar_admin_setup' );
function wpse19907_sidebar_admin_setup()
{
    if ( ! isset( $_POST['action'] ) || 'save-widget' != $_POST['action'] || empty( $_POST['add_new'] ) ) {
        return;
    }

    // We're adding a new widget to a sidebar
    global $wpse19907_sidebars_max_widgets;
    $sidebar_id = $_POST['sidebar'];

    if ( ! array_key_exists( $sidebar_id, $wpse19907_sidebars_max_widgets ) ) {
        return;
    }

    $sidebar = wp_get_sidebars_widgets();
    $sidebar = isset( $sidebars[$sidebar_id] ) ? $sidebars[$sidebar_id] : array();

    if ( count( $sidebar ) <= $wpse19907_sidebars_max_widgets[$sidebar_id] ) {
        die( 'mx' ); // Length must be shorter than 2, and unique
    }
}
    
respondido por el Jan Fabry 18.07.2011 - 22:09
4

para ayudarte con tu pregunta, tengo una sugerencia. Usemos el first-footer-widget-area presente en el archivo por defecto de la plantilla Twenty Ten sidebar-footer.php como ejemplo.

Como práctica recomendada y segura, primero realice una copia de seguridad para evitar dolores de cabeza.

El código de la plantilla original de Twenty Ten para presentar el primer widget de pie de página es:

<?php if ( is_active_sidebar( 'first-footer-widget-area' ) ) : ?>
       <div id="first" class="widget-area">
        <ul class="xoxo">
            <?php dynamic_sidebar( 'first-footer-widget-area' ); ?>
        </ul>
       </div><!-- #first .widget-area -->
<?php endif; ?>

Cambiemos, agregando un código con condiciones para limitar el número de widgets permitidos en esa área.

<?php if ( is_active_sidebar( 'first-footer-widget-area' ) ) : ?>
    <div id="first" class="widget-area">
    <?php
           $mysidebars = wp_get_sidebars_widgets();
           $total_widgets = count( $mysidebars['first-footer-widget-area'] );
           $limit_allowed=2;
    ?>
        <ul class="xoxo">
            <?php  if ($total_widgets > $limit_allowed) {
                echo 'Your '.$total_widgets.' added widgets goes over the allowed limit: <strong>'.$limit_allowed.'</trong>';
                } else { ?>
            <?php dynamic_sidebar( 'first-footer-widget-area' ); ?>
          <?php }; ?>
        </ul>

        </div><!-- #first .widget-area -->
<?php endif; ?>

Lo que hace este código modificado:

$mysidebars = wp_get_sidebars_widgets();
$total_widgets = count( $mysidebars['first-footer-widget-area'] );
$limit_allowed=2;

cuente el número de widgets en esa barra lateral y establezca un límite permitido (establecido por usted).

...
<?php  if ($total_widgets > $limit_allowed) {
            echo 'Your '.$total_widgets.' added widgets goes over the allowed limit: <strong>'.$limit_allowed.'</trong>';
       } else { ?>
            <?php dynamic_sidebar( 'first-footer-widget-area' ); ?>
<?php }; ?>
...

Si se alcanzó el límite permitido para los widgets en esa área, se mostrará un mensaje de advertencia que indica que, de lo contrario, se mostrará el widget.

Espero haberte ayudado con tu pregunta.

    
respondido por el Hans Zimermann 03.07.2011 - 22:40
0

Interessting Q. No descubrí mucho en un breve vistazo, pero aquí hay una conjetura: print_r( $GLOBALS['wp_registered_sidebars'] ); o print_r( $GLOBALS['sidebars'] ); o print_r( $GLOBALS['sidebars_widgets'] ); ...

    
respondido por el kaiser 14.06.2011 - 00:28
0

Puedes hacer lo siguiente para determinar el número de widgets.

Función :

$mysidebars = wp_get_sidebars_widgets() : te dará la lista de barras laterales y widgets utilizados en esas barras laterales.

$total_widgets = count( $mysidebars['my-sidebar-id'] ); : te dará el recuento del total de widgets en my-sidebar-id

Espero que esto resuelva tus dudas.

    
respondido por el Todd 30.06.2011 - 08:40

Lea otras preguntas en las etiquetas