API 호출에서 WordPress 커스터마이저의 선택 상자에 추가하는 방법은 무엇입니까?
WordPress 테마를 작업 중인데 사용자가 자신의 사이트에 사용할 글꼴을 선택할 수 있도록 선택 상자를 추가했습니다.Google Fonts API를 사용하여 900 및 그 이상을 수동으로 추가하는 것이 아니라 글꼴 목록을 가져오려고 했는데 API를 호출하면 반환된 데이터를 선택 상자에 옵션으로 추가할 수 없습니다.
이것은 나의 select box 클래스의 PHP 코드입니다.
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
}
}
그런 다음 다음 다음 코드를 사용하여 섹션, 설정 및 컨트롤을 커스터마이저에 추가했습니다.
// 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',
) ) );
다음 코드는 선택 상자에 옵션을 추가하는 것을 상정하고 있습니다.
$.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.")
}
});
#font-select를 body로 변경하면 옵션이 정상적으로 추가되지만 선택 상자에 추가하려고 해도 기능하지 않습니다.내가 왜 어떻게 이걸 할 수 있는지 알아?
다음 코드와 같이 커스터마이저 관리 패널의 선택 상자에 옵션 값을 추가할 수 있습니다.
고객의 요건에 관한 완전한 코드
- 스크립트에 구글 폰트 API 키만 추가하면 됩니다.
- 내가 'twentnineteen' 테마 슬러그 이름을 사용한 곳에서 당신은 테마 슬러그 이름을 사용할 수 있습니다.
3개의 파트가 있습니다.
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' );
스크립트 파일 추가
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' );
이제 마지막 스텝은 위에서 큐잉한 custom-discluse.discluse 파일에 다음 스크립트를 추가해 주세요.
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.")
}
});
});
이 코드를 사용해보니 정상적으로 작동합니다!
이게 도움이 됐으면 좋겠네요!
AJAX Success Callback이 다음 드롭다운을 찾고 있습니다.id
~하듯이font-select
다만, 드롭 다운의 ID는, 라벨에 근거하고 있습니다(우연히 다음과 같습니다).font
).
드롭다운의 ID는 다음 코드 행에 의해 생성됩니다.render_content
방법.
<?php echo str_replace(' ','-',strtolower(esc_html( $this->label ))); ?>
$this->label
여기서 참조하는 것은Fonts
스트롤러를 사용하고 있기 때문에fonts
다른 변수를 넘겨주셨으면 합니다.id
해당 변수를 사용하여 입력합니다.
언급URL : https://stackoverflow.com/questions/58114993/how-to-append-to-a-select-box-in-the-wordpress-customiser-from-an-api-call
'programing' 카테고리의 다른 글
확인란이 angularjs의 스코프에 바인딩되지 않음 (0) | 2023.03.20 |
---|---|
AngularJS 번호 입력 형식 보기 (0) | 2023.03.20 |
JSON 파일을 통해 payload를 curl로 전달하려면 어떻게 해야 합니까? (0) | 2023.03.20 |
WordPress는 계속해서 index.php 및 .htaccess 파일을 만들고 사용 권한을 0444로 변경합니다. (0) | 2023.03.20 |
Wordpress 내부에서 Larabel에서 인증된 사용자를 확인하시겠습니까? (0) | 2023.03.20 |