unzip_file()


WordPressのunzip_file()関数は、ZIPファイルを指定したディレクトリに解凍するために使用されます。この関数は、プラグインやテーマのインストール時に内部的に使用されることが多いです。

構文

unzip_file( string $file, string $to );

引数の説明:

  • $file(string) — 解凍するZIPファイルのパス。
  • $to(string) — 解凍先のディレクトリパス。

例1: 基本的なZIPファイルの解凍

この例では、指定されたZIPファイルを指定されたディレクトリに解凍します。

unzip_file('/path/to/archive.zip', '/path/to/destination/');

例2: プラグインのインストール時にZIPファイルを解凍

プラグインをインストールする際に、ZIPファイルを解凍する例です。

$result = unzip_file('/path/to/plugin.zip', WP_PLUGIN_DIR);
if (is_wp_error($result)) { echo '解凍中にエラーが発生しました。'; }

例3: テーマのインストール時にZIPファイルを解凍

テーマをインストールする際に、ZIPファイルを解凍する例です。

$result = unzip_file('/path/to/theme.zip', get_theme_root());
if (is_wp_error($result)) { echo '解凍中にエラーが発生しました。'; }

例4: 一時ディレクトリにZIPファイルを解凍

一時ディレクトリにZIPファイルを解凍する例です。

$result = unzip_file('/path/to/temp.zip', get_temp_dir());
if (is_wp_error($result)) { echo '解凍中にエラーが発生しました。'; }

例5: カスタムディレクトリにZIPファイルを解凍

カスタムディレクトリにZIPファイルを解凍する例です。

$result = unzip_file('/path/to/custom.zip', '/custom/path/');
if (is_wp_error($result)) { echo '解凍中にエラーが発生しました。'; }

例6: エラーハンドリング

解凍中にエラーが発生した場合のハンドリング例です。

$result = unzip_file('/path/to/archive.zip', '/path/to/destination/');
if (is_wp_error($result)) { echo 'エラー: ' . $result->get_error_message(); }

例7: ファイルの存在確認後に解凍

ZIPファイルが存在するか確認してから解凍する例です。

if (file_exists('/path/to/archive.zip')) { unzip_file('/path/to/archive.zip', '/path/to/destination/'); }

例8: 解凍後のファイルリストを取得

解凍後に解凍されたファイルのリストを取得する例です。

$result = unzip_file('/path/to/archive.zip', '/path/to/destination/');
if (!is_wp_error($result)) { $files = list_files('/path/to/destination/'); print_r($files); }

注意点

  • ZIPファイルのパスと解凍先のディレクトリパスは正しく指定する必要があります。
  • 解凍先のディレクトリに書き込み権限が必要です。
  • エラーハンドリングを適切に行うことで、問題が発生した場合に迅速に対処できます。

関連機能: