Site icon Hip-Hop Website Design and Development

Theme Customizer API Live Preview

I’m having some trouble with getting the text that I type in the input field to appear on the page whilst I type (live preview).

When I hit save and refresh, the changes are saved, they just for some reason won’t appear as I type. Any idea why the live preview might not be working? I believe I’m doing everything correctly.

functions.php

<?php

function tcx_register_theme_customizer( $wp_customize ) {

  $wp_customize->add_section(
    'tcx_notification_options',
    array(
      'title'     => 'Notification Bar',
      'priority'  => 201
    )
  );

  $wp_customize->add_setting(
  'tcx_notification_text',
    array(
      'default'            => 'Free International Shipping on Orders Over £100',
      'sanitize_callback'  => 'tcx_sanitize_notification_text',
      'transport'          => 'postMessage'
    )
  );

  $wp_customize->add_control(
  'tcx_notification_text',
    array(
      'section'  => 'tcx_notification_options',
      'label'    => 'Notification Text',
      'type'     => 'text'
    )
  );

add_action( 'customize_register', 'tcx_register_theme_customizer' );

function tcx_sanitize_notification_text( $input ) {
  return strip_tags( stripslashes( $input ) );
}

function tcx_customizer_live_preview() {
  wp_enqueue_script(
    'tcx-theme-customizer',
    get_template_directory_uri() . '/library/js/theme-customizer.js',
    array( 'jquery', 'customize-preview' ),
    '1.0.0',
    true
  );
}

add_action( 'customize_preview_init', 'tcx_customizer_live_preview' );

theme-customizer.js

(function( $ ) {
  "use strict";

  wp.customize('tcx_notification_text', function(value) {
    value.bind(function(to) {
      $('.notification-title').text(to);
    });
  });

})( jQuery );

header.php

<strong class="notification-title"><?php echo get_theme_mod( 'tcx_notification_text' ); ?></strong>