How to append to a select box in the WordPress customiser from an API call?
You can add Option value in select box in customizer admin panel as by below code :
Full code of your requirements
- you just have to add your google font api key in scripts
- where I have used 'twentynineteen' theme slug name you can use your theme slug name
There are 3 parts:
1) function mytheme_customize_register( $wp_customize ) { //All our sections, settings, and controls will be added here $wp_customize->add_section( 'fonts' , array( 'title' => __( 'Font', 'twentynineteen' ), 'priority' => 100, 'description' => __( 'Pick a font for your website.', 'twentynineteen' ) ) ); // Add the setting & control for the font $wp_customize->add_setting( 'font-select' , array( 'type' => 'select', 'default' => 'Roboto', 'transport' => 'postMessage', ) ); $wp_customize->add_control( 'font-select', array( 'type' => 'select', 'priority' => 10, // Within the section. 'section' => 'core', // Required, core or custom. 'description' => __( 'This is a date control with a red border.' ), 'choices' => array( // Optional. 'wordpress' => __( 'Roboto' ), 'hamsters' => __( 'Lato' ), 'jet-fuel' => __( 'Muli' ), ), 'label' => __( 'Font', 'twentynineteen' ), 'section' => 'fonts', 'settings' => 'font-select', ) ); } add_action( 'customize_register', 'mytheme_customize_register' );
now add scripts file
2) function add_font_scripts(){ wp_enqueue_script('custom_js_script', get_bloginfo('template_url').'/js/custom-scripts.js', array('jquery'));}add_action( 'admin_enqueue_scripts', 'add_font_scripts' );
now last step please add below script in this file custom-scripts.js which we just enqueue above
3) var $= jQuery;$(document).ready(function(){ $.ajax({ type: "GET", url: "https://www.googleapis.com/webfonts/v1/webfonts?key=apikey&sort=popularity&fields=items", dataType: "json", success: function (result, status, xhr){ var outputstate = []; console.log(result.items); for (var i = 0; i<result.items.length; i++){ var family = result.items[i].family; console.log(family); outputstate.push('<option value="'+ family +'">'+ family +'</option>'); $('#_customize-input-font-select').html(outputstate.join('')); } }, error: function (xhr, status, error) { alert("There was an error loading the Google fonts API: " + status + " " + error + " " + xhr.status + " " + xhr.statusText + "\n\nPlease save your changes and refresh the page to try again.") } }); });
I have try this code and It's Working fine!
I Hope this one is help you!
Your AJAX Success Callback is looking for the dropdown with id
as font-select
. However, the id of the Dropdown is based on the Label (which happens to be font
).
The ID of the dropdown is created by following line of code in render_content
method.
<?php echo str_replace(' ','-',strtolower(esc_html( $this->label ))); ?>
$this->label
here will refer to the Fonts
. Since you are using strtolower it will be fonts
. I suggest you pass another variable for the id
and populate it using that variable.