Ich arbeite an einem WordPress-Design und habe ein Auswahlfeld hinzugefügt, mit dem Benutzer eine Schriftart für ihre Website auswählen können. Ich dachte, ich würde die Google Fonts-API verwenden, um die Liste der Schriftarten abzurufen, anstatt alle 900 und so etwas manuell hinzuzufügen, aber wenn ich die API aufrufe, kann ich die zurückgegebenen Daten nicht als Optionen in das Auswahlfeld einfügen.
Dies ist der PHP-Code für meine Select-Box-Klasse:
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
}
}
Dann habe ich dem Customizer mit dem folgenden Code einen Abschnitt, eine Einstellung und eine Steuerung hinzugefügt:
// 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',
) ) );
Der folgende Code soll die Optionen an die Auswahlbox anhängen:
$.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.")
}
});
Wenn ich mich verändere #font-select zu Karosserie, es hängt die Optionen gut an, aber wie auch immer ich versuche, sie an das Auswahlfeld anzuhängen, es funktioniert einfach nicht. Irgendeine Idee, warum und wie ich das zum Laufen bringen kann?