Skip to content

Instantly share code, notes, and snippets.

@isuke01
Last active February 2, 2023 11:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save isuke01/1d5343a39995d26a86e8953246b0f483 to your computer and use it in GitHub Desktop.
Save isuke01/1d5343a39995d26a86e8953246b0f483 to your computer and use it in GitHub Desktop.
WP add option to Customizer
<?php
/**
* Customizer additional settings.
* To retrive the setting use get_theme_mod( 'setting_name' )
*/
class Customizer {
/**
* Class instance.
*
* @var self
*/
private static $instance;
/**
* Get active object instance
*
* @access public
* @static
* @return self
*/
public static function instance(): self {
if ( ! self::$instance ) {
self::$instance = new self();
}
return self::$instance;
}
/**
* Class constructor. Includes constants and init methods.
*
* @access public
* @return void
*/
public function __construct() {
$this->init();
}
/**
* Run action and filter hooks.
*
* @access private
* @return void
*/
private function init() {
// Setup the Theme Customizer settings and controls.
add_action( 'customize_register', [ get_called_class(), 'register' ] );
// Optionally we can register assets.
// add_action( 'customize_preview_init', [ get_called_class(), 'customizer_live_preview' ], 99 );
}
/**
* Register customizer options.
*
* @param \WP_Customize_Manager $wp_customize Theme Customizer object.
*/
public static function register( \WP_Customize_Manager $wp_customize ) {
// Add the custom theme options section.
// Add the header options.
$wp_customize->add_section(
'opt-header',
[
'title' => __( 'Site Header', 'textdomain' ),
'priority' => 31,
'capability' => 'edit_theme_options',
'description' => __( 'Here you can adjust header elenents.', 'textdomain' ),
]
);
$wp_customize->add_setting(
'show_extra_bar',
[
'capability' => 'edit_theme_options',
'default' => 0,
'transport' => 'refresh',
]
);
$wp_customize->add_control(
'show_extra_bar',
[
'type' => 'checkbox',
'section' => 'opt-header',
'priority' => 1,
'label' => __( 'Show bar above menu', 'textdomain' ),
]
);
}
**
* This outputs the javascript needed to automate the live settings preview.
* Also keep in mind that this function isn't necessary unless your settings
* are using 'transport'=>'postMessage' instead of the default 'transport'
* => 'refresh'
*
* @return void
*/
public static function customizer_live_preview() {
$source = get_template_directory() . '/build/customizer.js';
if ( file_exists( $source ) ) {
wp_enqueue_script(
'template-customizer',
get_template_directory_uri() . '/build/customizer.js',
[],
filemtime( $source ),
true
);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment