Add files programmatically to Order in Woocommerce - wordpress

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..

Related

Add custom bulk action "send email invoice" to orders list in Woocommerce

enter image description here
Hello How are you? I dont know how to bulk this action "email invoice /order details to customer" sometimes i have 70 orders that I need to send the email, and i have to do it one by one, i found some codes here but for other actions and i dont know how i can add that one, thanks a lot for the help!
function write_to_file($date_initial, $date_final) {
global $attach_download_dir, $attach_download_file;
// Opens/creates file
$myfile = fopen($attach_download_dir . '/' . $attach_download_file, "w") or die("Unable to open file!");
// Populates first line
fwrite($myfile, 'Date; Parent Order ID; Order ID' . PHP_EOL);
// Retrieves orders data
if ( isset($date_initial) && isset($date_final) ) $args = array( 'date_created' => $date_initial . '...' . $date_final );
if ( isset($date_initial) && empty($date_final) ) $args = array( 'date_created' => '>=' . $date_initial );
if ( empty($date_initial) && isset($date_final) ) $args = array( 'date_created' => '<=' . $date_final );
if ( empty($date_initial) && empty($date_final) ) $args = array( );
$orders = wc_get_orders( $args );
// Populates file with orders data
foreach ($orders as $order) {
$order_data = $order->get_data();
fwrite($myfile,
// Date of order creation
$order_data['date_created']->date('d/M/Y') . '; ' .
// Parent Order ID
'#' . ( ( $order->get_type() === 'shop_order' ) ? $order->get_id() : $order->get_parent_id() ) . '; ' .
// Order ID
'#' . $order->get_id()
)
}
}
I was looking for how to bulk email woocommerce order emails to customers, and came across this post. I tried asking a similar question - but thanks to 7uc1f3r for kicking my butt to do more work and find this answer myself.
With a bit of perseverance I figured it out by cobbling together a few bits and pieces from various posts.
I started with this post and used the email trigger code from this post.
I've tested this successfully on my production WooCommerce store.
The code below will add a new Bulk action to the WooCommerce -> Orders page called "Email Invoice / Order Details to Customers".
Select all the orders you want to receive the email, and choose this option. It will cycle through and send the WooCommerce template for Invoice/Order Email to each customer for each selected order. It gives a status update of how many emails were sent.
To use it, copy this code into your Wordpress theme's functions.php file:
/* Add to admin order list bulk dropdown a custom action 'Email Invoice / Order Details to Customers' */
add_filter( 'bulk_actions-edit-shop_order', 'email_invoice_bulk_action_orders_list', 20, 1 );
function email_invoice_bulk_action_orders_list( $actions ) {
$actions['send_emails'] = __( 'Email Invoice / Order Details to Customers', 'woocommerce' );
return $actions;
}
// Make the action from selected orders
add_filter( 'handle_bulk_actions-edit-shop_order', 'email_invoice_handle_bulk_action_orders_list', 10, 3 );
function email_invoice_handle_bulk_action_orders_list( $redirect_to, $action, $post_ids ) {
if ( $action !== 'send_emails' )
return $redirect_to; // Exit
$processed_ids = array();
foreach ( $post_ids as $orderid ) {
// Send customer order email
WC()->mailer()->emails['WC_Email_Customer_Invoice']->trigger($orderid);
// update count
$processed_ids[] = $post_id;
}
return $redirect_to = add_query_arg( array(
'send_emails' => '1',
'processed_count' => count( $processed_ids ),
'processed_ids' => implode( ',', $processed_ids ),
), $redirect_to );
}
// The results notice from bulk action on orders
add_action( 'admin_notices', 'email_invoice_bulk_action_admin_notice' );
function email_invoice_bulk_action_admin_notice() {
if ( empty( $_REQUEST['send_emails'] ) ) return; // Exit
$count = intval( $_REQUEST['processed_count'] );
printf( '<div id="message" class="updated fade"><p>' .
_n( 'Sent %s Order Invoice Email.',
'Sent %s Order Invoice Emails.',
$count,
'send_emails'
) . '</p></div>', $count );
}
Please test on a staging site first - just in case!
I hope this helps.
Israel.

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 );
}
}

How to Fetch the Shortcode Parameters Value in WordPress?

[amazon_s3 bucket=my_bucket_name object=my_file_name.ext]
Hi all i need to know how to fetch the parameter value in the above shortcode. For Example: Object is the attributes then how can i fetch the object value my_file_name.ext. I am using the woocommerce s3 plugin. I am not sure i customized the woocommerce to fetch the file name show in my account page here is the code.
function filename_wc_downloads( $link, $download )
{
$order = new WC_Order( $download['order_id'] );
$download_file_urls = $order->get_downloadable_file_urls(
$download['product_id'],
null,
$download['download_id']
);
foreach( $download_file_urls as $key => $value )
{
if( $value == $download['download_url'] )
{
$url_parts = explode( '/', parse_url( $key, PHP_URL_PATH ) );
$file_name = end( $url_parts );
$link = '<a href="'
. esc_url( $download['download_url'] )
. '">'
. $download['download_name']
. '</a> <small>( '
. $file_name
. ' )</small>';
}
}
return $link;
}
In a Woocommerce all products are uploaded into the media library of upload folder. The above code is to fetch the filename show in my account page if they using direct file path. If i pasted the above shortcode in the product url, that above code doesn't help to fetch the filename. so i need to know from the shortcode how can i get the object value based on this to show the file name.
amazon_s3 is your shortcode containing $atts bucket and object
when you use wordpress function add_shortcode('amazon_s3', 'your_function_name');
it automatically converts your attributes defined in [amazan_s3 .... to $atts
e.g.
function your_funnction_name($atts) {
extract(shortcode_atts(array(
'bucket' => '',
'object' => ''
), $atts));
return $object;
}

wordpress image attachment metadata without generating thumbnails

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 );
}

Custom upload directory to also change attachment meta

Please see below the filter I am using to change the upload directory for my custom post-type.
My custom post-type name is 'download'
My new directory for uploads in my custom post-type 'download' is now... wp-content/downloads/
The problem is in doing this, is that I my image thumbnails are missing because the attachment meta data is looking for the thumbnail in the original directory wp-content/uploads/.
How can I adjust my filter or fix the problem so the attachment data for this custom post-type only uses the new directory wp-content/downloads/
Thanks is advance for any advice or help.
Josh
add_filter( 'upload_dir', 'my_custom_upload_dir' );
function my_custom_upload_dir( $default_dir ) {
if ( ! isset( $_POST['post_id'] ) || $_POST['post_id'] < 0 )
return $default_dir;
if ( get_post_type( $_POST['post_id'] ) != 'download' )
return $default_dir;
$dir = WP_CONTENT_DIR . '/downloads';
$url = WP_CONTENT_URL . '/downloads';
$bdir = $dir;
$burl = $url;
$subdir = '';
if ( get_option( 'uploads_use_yearmonth_folders' ) ) {
$time = current_time( 'mysql' );
$y = substr( $time, 0, 4 );
$m = substr( $time, 5, 2 );
$subdir = "/$y/$m";
}
$dir .= $subdir;
$url .= $subdir;
$custom_dir = array(
'path' => $dir,
'url' => $url,
'subdir' => $subdir,
'basedir' => $bdir,
'baseurl' => $burl,
'error' => false,
);
return $custom_dir;
}
you could make custom posttype templates, and in those code custom get attachmentfunctions.
http://codex.wordpress.org/Post_Type_Templates
this custom code could look for the post_meta key: _wp_attached_file.
<?php $attachment_file = get_post_meta($current_post_id, '_wp_attached_file', false); ?>
http://codex.wordpress.org/Function_Reference/get_post_meta

Resources