Halloween Sale 15% off Ends in See the plans
PHP

Custom CSS Classes for Widgets

Adds a "CSS classes" field to every classic widget, so you can style individual widgets from your theme or a CSS snippet.

Don’t have WPIDE yet? Install it on your site

Code

add_action( 'in_widget_form', function ( $widget, $return, $instance ) {
    $value = isset( $instance['wpide_css_class'] ) ? $instance['wpide_css_class'] : '';

    echo '<p><label for="' . esc_attr( $widget->get_field_id( 'wpide_css_class' ) ) . '">CSS classes:</label>';
    echo '<input type="text" class="widefat" id="' . esc_attr( $widget->get_field_id( 'wpide_css_class' ) ) . '" name="' . esc_attr( $widget->get_field_name( 'wpide_css_class' ) ) . '" value="' . esc_attr( $value ) . '" /></p>';
}, 10, 3 );

add_filter( 'widget_update_callback', function ( $instance, $new_instance ) {
    $classes = isset( $new_instance['wpide_css_class'] ) ? explode( ' ', (string) $new_instance['wpide_css_class'] ) : array();

    $instance['wpide_css_class'] = implode( ' ', array_filter( array_map( 'sanitize_html_class', $classes ) ) );

    return $instance;
}, 10, 2 );

add_filter( 'dynamic_sidebar_params', function ( $params ) {
    global $wp_registered_widgets;

    $widget_id = isset( $params[0]['widget_id'] ) ? $params[0]['widget_id'] : '';
    $callback  = isset( $wp_registered_widgets[ $widget_id ]['callback'][0] ) ? $wp_registered_widgets[ $widget_id ]['callback'][0] : null;

    if ( ! $callback instanceof WP_Widget || ! isset( $params[1]['number'] ) ) {
        return $params;
    }

    $settings = $callback->get_settings();
    $classes  = isset( $settings[ $params[1]['number'] ]['wpide_css_class'] ) ? $settings[ $params[1]['number'] ]['wpide_css_class'] : '';

    if ( '' !== $classes ) {
        $params[0]['before_widget'] = preg_replace( '/class="/', 'class="' . esc_attr( $classes ) . ' ', $params[0]['before_widget'], 1 );
    }

    return $params;
} );

Notes

Separate several classes with spaces. Works with classic widgets and the Legacy Widget block.

How to add this snippet

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.