How to customize a shortcode using the customizer

High level description of what I ended doing, it is actually not too bad to do such an implementation and save you the effort of having different code for the widget and customizer forms, but there are many small details to take care of.

  • Store settings as a meta values for the post
  • Create proper customizer sections
    • Associate the section with a “virtual” option that is used only in the context of the customizer. The options stores the settings of all the shortcodes as an array.
    • When customizer is entered poulate the option from the meta values
    • When customizer saves update the meta values for whatever was changed and delete the option
    • To generate the “form”, take the widget form and do some regexp to add data-customize-setting-link attribute that will associate with the relevant setting

ob_start();
$widget->form(array());
$form = ob_get_clean();
$form = preg_replace_callback('/<(input|select)\s+.*name=("|\').*\[\d*\]\[([^\]]*)\][^>]*>/',
function ($matches) use ($p, $wp_customize, $meta) {
$setting = '_virtual-'.WIDGET_BASE_ID.'['.$p->ID.']['.$matches[3].']';
$wp_customize->add_setting( $setting, array(
'default' => $meta[$matches[3]], // set default to current value
'type' => 'option'
) );

  return str_replace('<'.$matches[1],'<'.$matches[1].' data-customize-setting-link="'.$setting.'"',$matches[0]);
    },
    $form
);
  • For the actual rendering code check if the page is being customized, and if so use the option, otherwise use the meta

Leave a Comment