WordPress主题自定义customizer增加多个复选框

在开发WordPress外贸主题过程中,为了实现将指定分类作为产品目录功能,而避免增加模板代码复杂性,减少if.else选择性,采用了在WordPress主题自定义customizer界面上,通过调出所有分类,以多个复选框显示,通过更直观方便地勾选自己想要的分类作为产品目录。在WordPress主题自定义customizer界面上增加此功能好处是:

  • 以后续业务人员操作过程中,能更加直接控制作为产品目录显示的分类
  • 操作简单,直接勾选即可
  • 减少主题模板的复杂性,提高模板显示效率
  • 减化模板,更加方便后续维护和升级

在WordPress主题自定义customizer增加多个复选框,有以下几个要点:

  • 如何将分类以复选框显示在customizer界面中
  • 如何控制JS勾选并传回数据到customizer界面中

第一步:建立后台主题自定义customizer界面

// #2 Select Category for catalog
// The category IDs are saved in the database as a comma separated string.
// Use method: $cat_slug = get_theme_mod( 'catalog_categories' );
add_action( 'customize_register', 'cq_exclude_cat_chkbox_register' );
function cq_exclude_cat_chkbox_register( $wp_customize ) {
	
	if (class_exists('WP_Customize_Control')) {
		class Cq_Category_Checkboxes_Control extends WP_Customize_Control {
			public $type = 'category-checkboxes';

			public function enqueue() {
				wp_enqueue_script('theme-customizer', get_template_directory_uri() . '/assets/js/theme-customizer.js' );
			}
		 
			public function render_content() {
		 
				// Displays checkbox heading
				echo '<span class="customize-control-title">' . esc_html( $this->label ) . '</span>';
				
				$multi_values = !is_array( $this->value() ) ? explode( ',', $this->value() ) : $this->value();
		 
				// Displays category checkboxes.
				foreach ( $this->choices as $value => $label ) {
					echo '<label><input type="checkbox" class="cq-category-checkbox" id= "'. esc_attr( $value ) .'" value="'. esc_attr( $value ) .'"> ' .  esc_html( $label ) . '</label><br>';    
				}
		 
				// Loads the hidden input field that stores the saved category list.
				?><input type="hidden" id="<?php echo esc_attr($this->id); ?>" name="<?php echo esc_attr($this->id); ?>" class="categories-catalog-vals" <?php $this->link(); ?> value="<?php echo esc_attr( implode( ',', $multi_values ) ); ?>"><?php
			}
		}		
	}	

	function cq_sanitize_favorite_fruit( $values ) {
		$multi_values = !is_array( $values ) ? explode( ',', $values ) : $values;
		return !empty( $multi_values ) ? array_map( 'sanitize_text_field', $multi_values ) : array();
	}

    $wp_customize->add_setting( 'catalog_categories', array(
		'type' => 'theme_mod',
		'default' => array(),
		'transport'   => 'postMessage',		
		'capability'  => 'edit_theme_options',
		'sanitize_callback' => 'cq_sanitize_favorite_fruit'
    ) ); 
    $wp_customize->add_control( new Cq_Category_Checkboxes_Control( $wp_customize,'catalog_categories', array(
		'settings'  => 'catalog_categories',
        'label'     => __( '#2: Select Categories as Catalog.', 'colinqi' ),        
        'section'   => 'more_customizing',
		'choices' => get_categories_select() 
    ) ) );		
}

第二步:编写JS传回复选框勾选数据

jQuery(window).load(function() {
	"use strict";

	jQuery('.categories-catalog-vals').each(function(){
		var catalog_values = jQuery(this).val().split(',');
		var id = jQuery(this).prop('id');
		//console.log(catalog_values);
		//console.log(id);

		jQuery('#' + id).closest('li').find('.cq-category-checkbox').each(function(){
			var elementID = jQuery(this).prop('id').split(',');
			//console.log(elementID);
			//console.log(elementID[0]);
			
			if( jQuery.inArray( elementID[0], catalog_values ) < 0 ) {
				jQuery(this).prop('checked', false);
			} else {
				jQuery(this).prop('checked', true);
			}				
		});					
	}); 

    // Sets listeners for checkboxes
    jQuery( '.customize-control-category-checkboxes input[type="checkbox"]' ).on('change',function() {		

		var checked_box = jQuery( this ).parents( '.customize-control' ).find( 'input[type="checkbox"]:checked' ).map(function() {	
			return this.value;
		}).get().join( ',' );
		
		jQuery( this ).parents( '.customize-control' ).find( '.categories-catalog-vals' ).val( checked_box ).trigger( 'change' );	

	 });	

});

以上JS代码需要放置在第一步调用的theme-customizer.js文件中。

第三步:如何在主题模板中调用此复选框数据

只需要在模板合适的地方插入以下语句即可。需要注意的是,此调出的数据为数据,请留意在不同地方便转换后使用。

$cat_slug = get_theme_mod( 'catalog_categories' );

完毕

Previous/Next

Say Something!

Leave a Reply