Sunday, 29 September 2019

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

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?



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

No comments:

Post a Comment