Skip to content

Instantly share code, notes, and snippets.

@agustinprosperi
Created November 29, 2016 10:31
Show Gist options
  • Save agustinprosperi/dbdd2392a05a40db19c617da2ca0592e to your computer and use it in GitHub Desktop.
Save agustinprosperi/dbdd2392a05a40db19c617da2ca0592e to your computer and use it in GitHub Desktop.
wp_insert_attachment from an existing file
<?php
add_action( 'init', function(){
if( !isset($_GET['test_adjuntar']) ) return false;
if ( !function_exists('media_sideload_image') ){
require_once( ABSPATH.'/wp-admin/includes/media.php' );
require_once( ABSPATH.'/wp-admin/includes/file.php' );
require_once( ABSPATH.'/wp-admin/includes/image.php' );
}
$uploadpath = wp_get_upload_dir();
//
$post_id = 16716;
$f_dir = '/2016/11/Desarrollador PHP experto WordPress _ Maquetador Web - Formularios de Google.pdf';
$file = $uploadpath['basedir'].$f_dir;
$title = preg_replace('/\.[^.]+$/', '', basename($file));
// Construct the attachment array.
$attachment = array(
'post_mime_type' => filetype( $file ), //'application/pdf'
'guid' => home_url().$f_dir,
'post_parent' => $post_id,
'post_title' => $title,
'post_content' => '',
);
// Save the attachment metadata
$id = wp_insert_attachment($attachment, $file, $post_id);
if ( !is_wp_error($id) ){
wp_update_attachment_metadata( $id, wp_generate_attachment_metadata( $id, $file ) );
}
var_dump($id);
exit();
} );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment