Insert Widget option into mark-up with register_sidebar

I have added a custom field to my all widgets in my theme, called “custom-title”. I have managed to save the field into the database for each widget, like so:

 s:12:"custom-title";s:17:"HELLO TEST ANCHOR"

I want to use this to add a data-attribute “custom-title” to the mark-up for each widget, on the before_widget argument. I want the final mark-up to look like this:

<div id="widget-id" class="widget classes" data-custom-title="HELLO TEST ANCHOR">

I want to do it using register_sidebar() so that it applies to ALL widgets that have a custom-title saved.

Here is the current arguments passed to register_sidebar:

      // Register Sidebar
      register_sidebar(
          Array(
              'id' => $sidebar_id,
              'name' => $arr_sidebar[0],
              'description' => $arr_sidebar[1],
              'before_widget' => '<div id="%1$s" class="widget %2$s" data-custom-title="">',
              'after_widget' => '</div>',
              'before_title' => '<h2>',
              'after_title' => '</h2>'
          )
      );

Is it possible to insert my custom-title into the correct place in this mark-up?

1 Answer
1

First you will replace this line <div id="%1$s" class="widget %2$s" data-custom-title=""> with <div id="%1$s" class="widget %2$s" data-custom-title="DCT">

Now add the filter in your functions.php file.

add_filter( 'widget_display_callback', 'add_custom_data_to_before_widget', 10, 3 );
function add_custom_data_to_before_widget( $instance, $widget_class, $args ) {
    if ( ! empty( $instance['title'] ) && ! empty( $instance['custom-title'] )) {
        $args['before_widget'] = str_replace('DCT', sanitize_text_field ( $instance['custom-title'] ), $args['before_widget']);
        $widget_class->widget( $args, $instance );
        return false;
    }
}

Hope that this will help you.

Leave a Comment