2

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?

0

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.

| improve this answer | |
  • 1
    Thank you for the suggestion, but this doesn't work. Instead of replacing the letters "DCT" with the content of the field "custom-title", it replaces ALL of the content (heading, image & text) of ALL of the widgets on the page with the content of one random widget. – Ila Aug 5 '14 at 15:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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