WP_Filesystemを使いなさい!と警告された際の対処方法

どっかから画像を取得して、保存し直す。 これをやろうとして「file_put_contents」を使ったらWordpress的にはWP_Filesystemを使えってさ。

WARNING: file_put_contents was found in the file 〇〇.php File operations should use the WP_Filesystem methods instead of direct PHP filesystem calls.

ぐぬぬ、どう書き換えればいいんだ・・・。困った。 ということで試行錯誤の結果以下でうまくいった。 WP_Filesystemの情報が少なかったので、参考までにアップ。

<?php
require_once(ABSPATH . 'wp-admin/includes/file.php');
$new_id='hogehoge';

$imgurl = 'http://xxx.xxx/xxxxxx.jpg';
if (WP_Filesystem($imgurl)){
global  $wp_filesystem;
$imgdata = $wp_filesystem->get_contents($imgurl);
}

if(WP_Filesystem($imgdata)){
global  $wp_filesystem;
$wp_filesystem->put_contents('../wp-content/uploads/'.$new_id.'.jpg',$imgdata);
}

?>