wordpress image attachment metadata without generating thumbnails - wordpress

i want to process all the attachments but without regenerating the thumbnails again. Right now i am using wp_generate_attachment_metadata()..but this takes long time for executing all the post attachments because of thumbanail creations. I just want serialize meta data array for faster execution.

You can write your own version of this function without thumbs generation, take a look here :
http://core.trac.wordpress.org/browser/tags/3.3.1/wp-admin/includes/image.php#L80
For example :
function my_generate_attachment_metadata( $attachment_id, $file ) {
$attachment = get_post( $attachment_id );
$metadata = array();
if ( preg_match('!^image/!', get_post_mime_type( $attachment )) && file_is_displayable_image($file) ) {
$imagesize = getimagesize( $file );
$metadata['width'] = $imagesize[0];
$metadata['height'] = $imagesize[1];
list($uwidth, $uheight) = wp_constrain_dimensions($metadata['width'], $metadata['height'], 128, 96);
$metadata['hwstring_small'] = "height='$uheight' width='$uwidth'";
// Make the file path relative to the upload dir
$metadata['file'] = _wp_relative_upload_path($file);
// fetch additional metadata from exif/iptc
$image_meta = wp_read_image_metadata( $file );
if ( $image_meta )
$metadata['image_meta'] = $image_meta;
}
return apply_filters( 'wp_generate_attachment_metadata', $metadata, $attachment_id );
}

Related

Replace space with hyphen for image filename on upload

I'm using the code bellow (I found it here on stack overflow from this post) to auto rename image filename and fill alt and title field based on post title.
The good thing is it's working, it's doing its job but problem is with filename : it's using post title with spaces, comas, etc. as filename, which is really not good. It's perfect for filling the title and alt fields but not for a filename.
So, just for the filename, I would like to add something to replace spaces by hyphen (and if possible remove potentials comas or other punctuation)
I thought that the part add_filter( 'sanitize_file_name', 'file_renamer', 10, 1 ); would to the job, but it's not.
But as I'm really not sure what I'm doing, and as I have poor PHP knowledge, I would be very grateful if you could teach me how to make it work :
function file_renamer( $filename ) {
$info = pathinfo( $filename );
$ext = empty( $info['extension'] ) ? '' : '.' . $info['extension'];
$name = basename( $filename, $ext );
if( $post_id = array_key_exists("post_id", $_POST) ? $_POST["post_id"] : null) {
if($post = get_post($post_id)) {
return $post->post_title . $ext;
}
}
$my_image_title = $post;
$file['name'] = $my_image_title . - uniqid() . $ext; // uniqid method
// $file['name'] = md5($name) . $ext; // md5 method
// $file['name'] = base64_encode($name) . $ext; // base64 method
return $filename;
}
add_filter( 'sanitize_file_name', 'file_renamer', 10, 1 );
/* Automatically set the image Title, Alt-Text, Caption & Description upon upload */
add_action( 'add_attachment', 'my_set_image_meta_upon_image_upload' );
function my_set_image_meta_upon_image_upload( $post_ID ) {
// Check if uploaded file is an image, else do nothing
if ( wp_attachment_is_image( $post_ID ) ) {
// Get the parent post ID, if there is one
if( isset($_REQUEST['post_id']) ) {
$post_id = $_REQUEST['post_id'];
} else {
$post_id = false;
}
if ($post_id != false) {
$my_image_title = get_the_title($post_id);
} else {
$my_image_title = get_post( $post_ID )->post_title;
}
// Sanitize the title: remove hyphens, underscores & extra spaces:
$my_image_title = preg_replace( '%\s*[-_\s]+\s*%', ' ', $my_image_title );
// Create an array with the image meta (Title, Caption, Description) to be updated
// Note: comment out the Excerpt/Caption or Content/Description lines if not needed
$my_image_meta = array(
'ID' => $post_ID, // Specify the image (ID) to be updated
'post_title' => $my_image_title, // Set image Title to sanitized title
'post_content' => $my_image_title, // Set image Description (Content) to sanitized title
);
// Set the image Alt-Text
update_post_meta( $post_ID, '_wp_attachment_image_alt', $my_image_title );
// Set the image meta (e.g. Title, Excerpt, Content)
wp_update_post( $my_image_meta );
}
}
Thanks for your help !
So solution was replacing post_title by post_name in file_renamer function.
Exactly this part : change return $post->post_title . $ext; and replace it with return $post->post_name . $ext;
And it's working. On upload, this function is renaming the file name with hyphens and filling title, alt text and description fields based on Post Title (without hyphens).

Conditionally change upload directory on XMLRPC call according to username

I've searched seemingly every relevant question on this but I'm stuck, as none of them address the particular case of uploads through XML RPC.
I want to conditionally change the Wordpress file upload directory, only if the file is coming in through an XML RPC call and only if the call is coming in from a particular user.
My approach is based on a combination of this Answer, this Answer and the Codex.
Here's what I tried with no luck:
add_filter( 'xmlrpc_methods', 'call_intercept1' );
function call_intercept1( $methods ) {
$methods[ 'metaWeblog.newMediaObject' ] = 'custom_upload1';
return $methods;}
function custom_upload1( $args ) {
global $wpdb;
$username = $this->escape( $args[1] );
$password = $this->escape( $args[2] );
$data = $args[3];
$name = sanitize_file_name( $data['name'] );
$type = $data['type'];
$bits = $data['bits'];
if ( !$user = $this->login($username, $password) )
return $this->error;
if ( $username = "XXX" ) {
add_filter('upload_dir', 'custom_upload_dir1');
}
$upload = wp_upload_bits($name, null, $bits);
if ( ! empty($upload['error']) ) {
/* translators: 1: file name, 2: error message */
$errorString = sprintf( __( 'Could not write file %1$s (%2$s).' ), $name, $upload['error'] );
return new IXR_Error( 500, $errorString );
}
return $upload;
}
function custom_upload_dir1( $param ){
$custom_dir = '/the-desired-directory';
$param['path'] = $param['path'] . $custom_dir;
$param['url'] = $param['url'] . $custom_dir;
error_log("path={$param['path']}");
error_log("url={$param['url']}");
error_log("subdir={$param['subdir']}");
error_log("basedir={$param['basedir']}");
error_log("baseurl={$param['baseurl']}");
error_log("error={$param['error']}");
return $param;
}
The file is being uploaded correctly, but the conditional directory change isn't happening.
Does someone know why that would be?
I was able to get this worked out, essentially using Ulf B's Custom Upload Dir as a model and simplifying it from there.
For anyone else facing the same problem, here's what works:
// XMLRPC Conditional Upload Directory
add_action('xmlrpc_call', 'redirect_xmlrpc_call');
function redirect_xmlrpc_call($call){
if($call !== 'metaWeblog.newMediaObject'){return;}
global $wp_xmlrpc_server;
$username = $wp_xmlrpc_server->message->params[1];
$data = $wp_xmlrpc_server->message->params[3];
if($username !== "XXX"){return;}
else {custom_pre_upload($data);}}
function custom_pre_upload($data){
add_filter('upload_dir', 'custom_upload_dir');
return $data;}
function custom_post_upload($fileinfo){
remove_filter('upload_dir', 'custom_upload_dir');
return $fileinfo;}
function custom_upload_dir($path){
if(!empty($path['error'])) { return $path; } //error; do nothing.
$customdir = '/' . 'your-directory-name';
$path['subdir'] = $customdir;
$path['path'] .= $customdir;
$path['url'] .= $customdir;
return $path;}

Wordpress Updating Attachment Data

I'm attempting to add a feature to a plugin that extends media management. This feature would allow you to rename an attachment file. I've been able to complete this with the following code.
public function update_attachment_filename( $post_ID ) {
// Get path to existing file
$file = get_attached_file( $post_ID );
$path = pathinfo( $file );
// Generate new file name
$file_updated = $path['dirname'] . '/' . $_POST['update_filename'] . '.' . $path['extension'];
// Update the name and reference to file
rename( $file, $file_updated );
update_attached_file( $post_ID, $file_updated );
}
While the original file gets renamed using the above method, all additional image sizes defined in the plugins/theme are not updated. I'm struggling to figure out the best way to accomplish this task.
I've looked into wp_update_attachment_metadata() and wp_generate_attachment_metadata() but am unsure whether they will give me the desired functionality.
Additionally I've looked into something such as:
$file_meta = wp_get_attachment_metadata( $post_ID );
foreach( $file_meta['sizes'] as $image ) {
// Do something
}
Any nudge in the right direction would be greatly appreciated.
Thanks!
I was able to utilize both the wp_generate_attachment_metadata() and the wp_update_attachment_metadata() function to achieve the desired end result.
public function update_attachment_filename( $post_ID ) {
if( isset( $_POST['update_filename'] ) && ! empty( $_POST['update_filename'] ) ) {
// Get path to existing attachment
$file = get_attached_file( $post_ID );
$path = pathinfo( $file );
// Create new attachment name
$file_updated = $path['dirname'] . '/' . $_POST['update_filename'] . '.' . $path['extension'];
// Update the attachment name
rename( $file, $file_updated );
update_attached_file( $post_ID, $file_updated );
// Update attachment meta data
$file_updated_meta = wp_generate_attachment_metadata( $post_ID, $file_updated );
wp_update_attachment_metadata( $post_ID, $file_updated_meta );
}
}

Add files programmatically to Order in Woocommerce

I'm using the "woocommerce_order_status_completed" hook to create a file dynamically after the user has paid for the order.
I need to add this file to his downloadable area in that order in this hooks.
Any ideias how to attach a file to a order?
woocommerce_order_status_completed you can add below code...
First store the file you have created in uploads using media_handle_upload
if($_FILES){
//if u don't want to $post_id u gan give 0
$attachment_id = media_handle_upload( 'abe_update_epub', $post_id );
if ( is_wp_error( $attachment_id ) ) {
$errors = $attachment_id->get_error_messages();
foreach( $errors as $error ){
echo $error;
}
echo 'There was an error uploading the image';
} else {
// NEW FILE: Setting the name, getting the url and and Md5 hash number
$file_name = 'Epub Files';
$file_url = wp_get_attachment_url($attachment_id);
$md5_num = md5( $file_url );
// Inserting new file in downloadable files
$files[$md5_num] = array(
'name' => $file_name,
'file' => $file_url
);
// Updating database with the new array
$order = new WC_Order($order_id);
if(!empty($files)){
update_post_meta($order->ID,_files,$files));
}
// Displaying a success notice
echo 'The image was uploaded successfully!';
}
}
Hopes this help u..

Upload media file from external URL to WordPress Media Library

I want to upload a file from external URL to the WordPress Media Library (that is common to ALL POSTS/PAGES). The return value I want to get is attachment ID in order to inject them into a shortcode (e.g. img).
I tried using IMEDIA_HANDLE_SIDELOAD but I got lost with $_FILES settings.
However, I am not sure about the parameters:
Is this the right function?
where in the code (aFile) should I place the URL I want to download from?
What is the "tmp_name" and "name"?
See my code:
// my params
$post_id = 0; // is this what makes it common to all posts/pages?
$url = 'www.some_external_url.com/blabla.png';
// example from some forum
$filepath = '/relative/path/to/file.jpg';
$wp_filetype = wp_check_filetype( basename( $filepath ), null );
$aFile["name"] = basename( $filepath );
$aFile["type"] = $wp_filetype;
$afile["tmp_name"] = $filepath;
$attach_id = $media_handle_sideload( $aFile, $post_id, 'sometitle' );
Solution:
private function _uploadImageToMediaLibrary($postID, $url, $alt = "blabla") {
require_once("../sites/$this->_wpFolder/wp-load.php");
require_once("../sites/$this->_wpFolder/wp-admin/includes/image.php");
require_once("../sites/$this->_wpFolder/wp-admin/includes/file.php");
require_once("../sites/$this->_wpFolder/wp-admin/includes/media.php");
$tmp = download_url( $url );
$desc = $alt;
$file_array = array();
// Set variables for storage
// fix file filename for query strings
preg_match('/[^\?]+\.(jpg|jpe|jpeg|gif|png)/i', $url, $matches);
$file_array['name'] = basename($matches[0]);
$file_array['tmp_name'] = $tmp;
// If error storing temporarily, unlink
if ( is_wp_error( $tmp ) ) {
#unlink($file_array['tmp_name']);
$file_array['tmp_name'] = '';
}
// do the validation and storage stuff
$id = media_handle_sideload( $file_array, $postID, $desc);
// If error storing permanently, unlink
if ( is_wp_error($id) ) {
#unlink($file_array['tmp_name']);
return $id;
}
return $id;
}

Resources