Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

We develop a new WordPress site with a new theme developed exclusively for this site.

Some widgets of the same type (such as two "Bookmarks" widgets) should be styled differently (that is have different CSS).

My question: In this case, should I use two Bookmarks widgets or hard-code it into the theme?

I can write CSS specifically for these widgets having their ID, but this seems inelegant, especially because it would be broken if somebody removed my widget and then add his own similar widget.

Widgetize or hard-code?

share|improve this question
add comment

2 Answers

The general concept on dynamic sidebars

Basically WP loops through the global $wp_registered_widgets and builds the widget depending on it's arguments. You can intercept them easily:

Use a filter

You can use the dynamic_sidebar_params to add a class to target specific widgets:

// SHOW the params for better insights
function wpse44903_dump_sidebar_params( $params )
{
    echo '<pre>';
    print_r( $params );
    echo '</pre>';

    return $params;
}
add_filter( 'dynamic_sidebar_params', 'wpse44903_dump_sidebar_params' );

Then you can simply alter whatever you need (depending on your situation):

// ALTER the params to your needs
function wpse44903_alter_sidebar_params( $params )
{
    // remove trailing and leading white space and use only lower case characters to be on the save side of things
    if ( 'YOUR WIDGET NAME' === trim( strtolower( $params[0]['widget_name'] ) ) )
    {
        // do whatever you need to do.
        // @example:
        foreach ( $wp_registered_widgets as $widget )
            if ( in_array( $params[0]['widget_name'], $widget ) )
                print_r( $widget );
    }

    return $params;
}
add_filter( 'dynamic_sidebar_params', 'wpse44903_alter_sidebar_params' );

Note: This is not tested and maybe needs some bug fixing. Be sure to turn WP_DEBUG to TRUE in your wp-config.php file.

share|improve this answer
add comment

Taking the widget route definitely seems like to clean way to me. Note that you can also manually display a widget in the sidebar via the the_widget() function. This way the user can't remove the widget.

An alternative approach may be to build in a style selection dropdown in the widget to give the user the power to choose the applicable style. In your widget you can then add a CSS class to the widget wrapper. Better than styling based on an ID that can change, like mywidget-5.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.