Skip to content

Instantly share code, notes, and snippets.

@MarceloGlez
Last active November 27, 2022 20:27
Show Gist options
  • Save MarceloGlez/1156881adc8eab2c9e671afc90e46620 to your computer and use it in GitHub Desktop.
Save MarceloGlez/1156881adc8eab2c9e671afc90e46620 to your computer and use it in GitHub Desktop.
Fuerza descarga de archivos desde url externa en Wordpress. Nota: Comprobar comportamiento global de WP con previo backup.
/**
* Código al functions.php del child theme.
* Se podrá descargar archivos en cualquier formato desde una url externa en nuestro dominio.
* Para usarlo, por ejemplo definir enlaces así:
* https://tudominio.com/download?url=https://dominio-externo.com/archivo.mp3
*/
$url = $_GET['url'];
if ( ! empty( $url ) ) {
require_once ABSPATH . 'wp-load.php';
require_once ABSPATH . 'wp-admin/includes/admin.php';
$tmp = download_url( esc_url( $url ), 3000, true );
$file_array = array(
'name' => basename( $url ),
'tmp_name' => $tmp,
);
if ( is_wp_error( $tmp ) ) {
wp_delete_file( $tmp );
return '';
}
$overrides = array( 'test_form' => false );
if ( isset( $post_data['post_date'] ) && substr( $post_data['post_date'], 0, 4 ) > 0 ) {
$time = $post_data['post_date'];
} else {
$post = get_post( $post_id );
if ( $post && substr( $post->post_date, 0, 4 ) > 0 ) {
$time = $post->post_date;
} else {
$time = current_time( 'mysql' );
}
}
$file = wp_handle_sideload( $file_array, $overrides, $time );
if ( isset( $file['error'] ) ) {
return new WP_Error( 'upload_error', $file['error'] );
}
$url = $file['url'];
$type = $file['type'];
$file = $file['file'];
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($file).'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
flush();
readfile($file);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment