Last active
August 23, 2019 19:22
-
-
Save giovanemachado/c800db1cc89e5fefe8d1d6b5dffa8e09 to your computer and use it in GitHub Desktop.
Esse snippet cria attachments no wordpress. Lê uma pasta com várias imagens, criando um looping nelas e retornando os IDs dos attachments. Baseado em algumas respostas no stackoverflow
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Caminho do servidor | |
$where_read = ABSPATH . 'caminho/para/os/arquivos'; | |
// Pega apenas arquivos, ignorando o que não tiver extensão ( pastas ) | |
$files_array = glob( $where_read . "/*.{*}", GLOB_BRACE ); | |
$upload_dir = wp_upload_dir(); | |
foreach( $files_array as $file ): | |
/** | |
* | |
* $file aqui tem que ser o caminho completo no servidor (/home/[dominio]/public_html/wp-content/uploads/arquivo.jpg) | |
* | |
*/ | |
$image_url = $file; | |
$image_data = file_get_contents( $image_url ); | |
$filename = basename( $image_url ); | |
if ( wp_mkdir_p( $upload_dir['path'] ) ) { | |
$file = $upload_dir['path'] . '/' . $filename; | |
} else { | |
$file = $upload_dir['basedir'] . '/' . $filename; | |
} | |
file_put_contents( $file, $image_data ); | |
$wp_filetype = wp_check_filetype( $filename, null ); | |
$attachment = [ | |
'post_mime_type' => $wp_filetype['type'], | |
'post_title' => sanitize_file_name( $filename ), | |
'post_content' => '', | |
'post_status' => 'inherit' | |
]; | |
// Armazena os ids dos attachments. | |
$attach_id[] = wp_insert_attachment( $attachment, $file ); | |
require_once( ABSPATH . 'wp-admin/includes/image.php' ); | |
// Gera os metadatas necessários para que os attachments funcionem normalmente. | |
$attach_data = wp_generate_attachment_metadata( $attach_id, $file ); | |
wp_update_attachment_metadata( $attach_id, $attach_data ); | |
endforeach; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment