如何让主题定制器中的自定义字段实时更新预览窗口中的元素?

时间:2021-09-08 作者:Nadal

I created a custom field for theme customizer, and all works fine to display the field, save the value to the DB and retrievable via get_theme_mod(), but it does not live update in the preview window. I have to reload the page to see the change.

The preview does refresh on each change of the fields and the Publish button is activated, but now I need the change to be detected and processed by the wp.customize javascript API.

The result from the custom field coding

image of the custom field result

Based on multiple searches, I have tried the following methods without success. Note this is just part of the code. The retrieved value uses the respective ID for each field setting which are head1font and head1size but the below is just of one. The code shows the two methods tried, but note that both are not used at the same time.

add_action(\'customize_controls_print_scripts\', function() 
{
  echo\'
  <script>
    jQuery(function($) {
     // setting.bind method
      wp.customize("head1font", function(setting) {
        setting.bind(function(value) {
            $("h1.pagetitle").css("font-family",value);
        });
      });

    // other method tried value.bind
      wp.customize("head1font", function(value) {
        value.bind(function(newval) {
            $("h1.pagetitle").css("font-family",newval);
        });
      });
    });
  </script>
 \';
});

The console note does not seem applicable. The following is the notice when a change action occur.

Error parsing a meta element\'s content: \';\' is not a valid key-value pair separator. Please use \',\' instead.

I am now at a loss for a solution so I am seeking tips to make this work.

1 个回复
最合适的回答,由SO网友:Nadal 整理而成

我已经定义了一个解决方案。这个transport 必须更改默认类型refreshpostMessage 使用自定义JS指令。

add_action(\'customize_register\', function($mgr) 
{
  //load the custom field class file
  include_once LIBPATH.\'/classTplFormat.php\';

  // moved the JS into a file and loaded via enqueue
  // ASSETURL is a constant that holds theurl to the assets folder
  add_action(\'customize_preview_init\', function() {
    wp_enqueue_script(\'tpl-customizer\', ASSETURL.\'/tpl-customizer.js\',[],\'\',true);
  });

  // the fields are in the custom class and too much to post but it follows
  // similar method as the core customizer eg: add_panel(), add_section(), add_setting()
  $mgr->add_control(new TplFormat($mgr, \'tplformat\',[]));
  //set the transport method to the specific field
  $mgr->get_setting(\'head1font\')->transport = \'postMessage\';
});

JS

(function($) {
    "use strict";
    wp.customize("head1font", function(value) {
        value.bind(function(value) {
            $("h1.pagetitle").css("font-family",value);
        });
    });
})(jQuery);

相关推荐