Home » Php » javascript – How to append to a select box in the WordPress customiser from an API call?

javascript – How to append to a select box in the WordPress customiser from an API call?

Posted by: admin July 12, 2020 Leave a comment

Questions:

I’m working on a WordPress theme and I’ve added a select box to allow users to select a font for their site. I figured I’d use the Google Fonts API to grab the list of fonts rather than add all 900-and-something manually, but when I call the API I’m unable to append the returned data as options in the select box.

This is the PHP code for my select box class:

    class Customize_Select_Control extends WP_Customize_Control {
        public $type = 'select';

        public function render_content() {
            ?>
            <label>
                <span class="customize-control-title"><?php echo esc_html( $this->label ); ?></span>
                <select <?php $this->link(); ?> id="<?php echo str_replace(' ','-',strtolower(esc_html( $this->label ))); ?>-select">
                    <option value="<?php echo $this->value(); ?>" selected><?php echo $this->value(); ?></option>
                </select>
            </label>
            <?php
        }
    }

I’ve then added a section, setting and control to the customiser using the following code:

    // Add Font Section
    $wp_customize->add_section( 'fonts' , array(
        'title' => __( 'Font', 'wordpress' ),
        'priority' => 100,
        'description' => __( 'Pick a font for your website.', 'wordpress' )
    ) );

    // Add the setting & control for the font
    $wp_customize->add_setting( 'font-select' , array(
        'default'   => 'Open Sans',
        'transport' => 'postMessage',
    ) );
    $wp_customize->add_control( new Customize_Select_Control( $wp_customize, 'font-select', array(
        'label'      => __( 'Font', 'wordpress' ),
        'section'    => 'fonts',
        'settings'   => 'font-select',
    ) ) );

The following code is supposed to append the options to the select box:

     $.ajax({
        type: "GET",
        url: "https://www.googleapis.com/webfonts/v1/webfonts?key=[REDACTED]&sort=popularity&fields=items",
        dataType: "json",
        success: function (result, status, xhr){
          console.log(result.items);
          for (var i = 0; i<result.items.length; i++){
            var family = result.items[i].family;
            console.log(family);
            $('#font-select').append(`<option value="${family}">${family}</option>`);
          }
        },
        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.")
        }
      });

If I change #font-select to body, it appends the options just fine, but however I try and append them to the select box, it just doesn’t work. Any idea why and how I can make this work?

How to&Answers:

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!

Answer:

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.