WP_Filesystem in custom customize control
-
29-09-2020 - |
Question
I'm currently trying to edit the following file so it uses the WP_Filesystem methods instead of direct PHP filesystem calls: google-font-dropdown-custom-control.php
My current code looks as follows:
function mytheme_customize_register( $wp_customize ) {
$wp_customize->add_section('fonts', array(
'title' => 'Font',
'priority' => 40
));
$wp_customize->add_setting( 'google_webfont' , array(
'default' => 'Open Sans',
'transport' => 'refresh',
) );
if (false === ($creds = request_filesystem_credentials('customize.php', '', false) ) ) {
// if we get here, then we don't have credentials yet,
// but have just produced a form for the user to fill in,
// so stop processing for now
return true; // stop the normal page form from displaying
}
// now we have some credentials, try to get the wp_filesystem running
if ( ! WP_Filesystem($creds) ) {
// our credentials were no good, ask the user for them again
request_filesystem_credentials('customize.php', '', true);
return true;
}
global $wp_filesystem;
require_once('inc/google-font-dropdown-custom-control.php');
$wp_customize->add_control( new Google_Font_Dropdown_Custom_Control( $wp_customize, $wp_filesystem, 'google_font_setting', array(
'label' => 'Title Font',
'section' => 'fonts',
'settings' => 'google_webfont'
) ) );
}
add_action( 'customize_register', 'mytheme_customize_register' );
This however throws me the following error:
Call to undefined function request_filesystem_credentials()
It seems like you can't use the Filesystem in the Theme Customizer? What would the solution be, any tips?
Solution
To cache something you can use the Transients API (thanks @Otto), get_transient()
to see if it exists already exists, if not then fetch the data and store it in a transient with set_transient()
.
if (get_transient('mytheme_webfonts')) {
$content = get_transient('mytheme_webfonts');
}
else{
$googleApi = 'https://www.googleapis.com/webfonts/v1/webfonts?sort=alpha&key={API_KEY}';
$fontContent = wp_remote_get( $googleApi, array('sslverify' => false) );
$content = json_decode($fontContent['body']);
set_transient( 'mytheme_webfonts', $content, WEEK_IN_SECONDS );
}
Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange