Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Category Dropdown Control
/**
* Make sure that custom controls are only defined in the Customizer
*/
if ( class_exists( 'WP_Customize_Control' ) ) :
/**
* A custom category dropdown control for the Customizer
*/
class Theme_Slug_Category_Dropdown_Control extends WP_Customize_Control {
/**
* Render Control
*/
public function render_content() {
$categories = get_categories( array( 'hide_empty' => false ) );
if ( ! empty( $categories ) ) : ?>
<label>
<span class="customize-control-title"><?php echo esc_html( $this->label ); ?></span>
<select <?php $this->link(); ?>>
<option value="0"><?php esc_html_e( 'All Categories', 'theme-slug' ); ?></option>
<?php
foreach ( $categories as $category ) :
printf( '<option value="%s" %s>%s</option>',
absint( $category->term_id ),
selected( $this->value(), $category->term_id, false ),
esc_html( $category->name . ' (' . $category->count . ')' )
);
endforeach;
?>
</select>
</label>
<?php
endif;
}
}
endif;
/**
* Adds Featured Content section and category select setting.
*
* @param WP_Customize_Manager $wp_customize The Customizer object.
*/
function theme_slug_customize_register( $wp_customize ) {
// Add featured content section.
$wp_customize->add_section( 'theme_slug_featured_category', array(
'title' => esc_html__( 'Featured Content', 'theme-slug' ),
'priority' => 120,
) );
// Add featured category setting and control.
$wp_customize->add_setting( 'featured_category', array(
'default' => 0,
'sanitize_callback' => 'absint',
'transport' => 'refresh',
) );
$wp_customize->add_control( new Theme_Slug_Category_Dropdown_Control( $wp_customize, 'featured_category', array(
'label' => esc_html__( 'Featured Category', 'theme-slug' ),
'section' => 'theme_slug_featured_category',
) ) );
}
add_action( 'customize_register', 'theme_slug_customize_register' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.