Ich habe das folgende Problem mit einer WordPress-Installation auf einem VPS-Server. Ich versuche, von einer JSON-Datei zu lesen, aber die zurückgegebene Adresse von get_template_directory()
ist falsch:
$url = get_template_directory() . '/inc/includes/acf-fonticonpicker'; $json_file = trailingslashit($url) . 'icons/selection.json'; if($wp_filesystem->exists($json_file)){ $json_content = $wp_filesystem->get_contents($json_file); }
$ json_file ist leer, weil die JSON-Datei nicht gefunden wurde. Die zurückgegebene Adresse ist:
/var/www/domainname/data/www/domain/wp-content/themes/couponhut/inc/includes/acf-fonticonpicker/icons/selection.json
und die Datei ist genau dort,
Was mache ich falsch? Jede Hilfe wird sehr geschätzt!
Sie können Daten auf Ihrem Server mit file_get_contents()
lesen. Wenn Sie sicherstellen möchten, dass die Datei vorhanden und lesbar ist, verwenden Sie is_readable()
. Sie müssen in diesem Fall nicht unbedingt trailingslashit()
, da Sie den URI selbst konstruieren.
// path to file under current theme $json_file = get_template_directory() . '/inc/includes/acf-fonticonpicker/icons/selection.json'; // make sure the file exists and is readable if ( is_readable( $json_file ) ) { // pull the data but don't give an error if there is a problem if ( ! empty ( $json_content = @file_get_contents( $json_file ) ) ) { // convert to an array $json_array = json_decode( $json_content, true ); } else { // show error message here } }
Leider ist file_get_contents()
möglicherweise in Theme Check markiert.
Dateisysteme sind lustig, wenn Sie wissen, dass es existiert, dann ist es möglich, dass /
und müssen gelegentlich im Pfad ausgetauscht werden.
// BEFORE // /vagrant/site/wp-content/themes/twentysixteen/inc/includes/acf-fonticonpicker/icons/selection.json $json_file = str_replace('/', '\\', $json_file); or $json_file = str_replace('/', '\\\\', $json_file); // AFTER // \vagrant\site\wp-content\themes\twentysixteen\inc\includes\acf-fonticonpicker\icons\selection.json
Ein anderer Weg ist der Zugriff über die URL.
// url of file $json_file = get_template_directory_uri() . '/inc/includes/acf-fonticonpicker/icons/selection.json'; // request the file $response = wp_remote_get( $json_file ); try { // Note that we decode the body's response since it's the actual JSON feed $json = json_decode( $response[ 'body' ], true ); } catch( Exception $ex ) { $json = NULL; }