Envíar email a clientes que hayan comprado producto descargable cuando se actualiza

Ttremendamente útil cuando vendemos productos digitales con WooCommerce. Este snippet envía un email de notificación a los clientes que hayan comprado un producto cuando este se actualiza. De esta forma cuando haya una nueva versión del producto descargable automáticamente woocommerce envía un email al cliente avisándole de que puede descargar una nueva versión.

Después de introducir el snippet podremos ver que se añade una nueva funcionalidad en la ficha de producto:

Enviar email a clientes que hayan comprado un producto descargable cuando se actualiza

 

Para configurar el texto del email, solo tienes que escribirlo en el editor que verás en la sección “Mensaje de notificación de la actualización”, en la misma página de edición del producto.

enviar-email-producto-actualizado-woocommerce

 

Snippet para envíar un email a los clientes que hayan comprado un producto cuando este se actualiza

// Envía email de notificación a los clientes que hayan comprado un producto cuando este se actualiza
if ( in_array( 'woocommerce/woocommerce.php', get_option( 'active_plugins' ) ) ){

	function post_published_notification( $ID ) {
	
		global $post;
		$customers_info = array();
		$notification_message = '';
	
		$orders = get_posts( array(
			'post_type'   => 'shop_order',
			'posts_per_page' => -1,
			'post_status' => array( 'wc-completed' )
			) );
	
		if( !empty( $orders ) && ( 'yes' == get_post_meta( $ID, 'updates_notification', true ) ) ){
	
			foreach ($orders as $key => $order ) {
	
				$order_object = new WC_Order( $order->ID );
	
				foreach ( $order_object->get_items() as $key => $item ) {
	
					if ( $item[ 'product_id' ] == $ID ) {
	
						$download_item_info = null !== $order_object->get_item_downloads( $item )? $order_object->get_item_downloads( $item ) : '';
						$customers_info[] = array( 'name' => $order_object->billing_first_name, 
							'email' => $order_object->billing_email,
							'donwloads_info' => $download_item_info
							);
					}
				}
			}
	
			if ( !empty( $customers_info ) ) {
	
				add_filter( 'wp_mail_content_type', function(){ return 'text/html'; } );
				foreach ( $customers_info as $key => $customer ) {
	        			//Clean up headers
					$headers = array();
	
					// Get notification message content
					$notification_message = wpautop( get_post_meta( $ID, 'update_notification_message', true ) );
	
					$author = $post->post_author; /* Post author ID. */
					$name = $customer[ 'name' ];
					$email = $customer[ 'email' ];
					$title = $post->post_title;
					$permalinks = get_email_format_permalinks( $customer[ 'donwloads_info' ] );
					$edit = get_edit_post_link( $ID, '' );
					$to = sprintf( '%s <%s>', $name, $email );
					$subject = sprintf( 'Hay una nueva versión disponible de %s', $title );
	
					$notification_message = str_replace( '{{name}}' , $name, $notification_message );
	
					if ( $permalinks ) {
						
						$plugin_downloads = create_downloads_list( isset( $permalinks[ 'plugin_downloads' ] )? $permalinks[ 'plugin_downloads' ] : array() );
						$documentation_downloads = create_downloads_list( isset( $permalinks[ 'documentation_downloads' ] )? $permalinks[ 'documentation_downloads' ] : array() );
						$notification_message = str_replace( '{{plugin_downloads}}' , $plugin_downloads, $notification_message );
						$notification_message = str_replace( '{{documentation_downloads}}' , $documentation_downloads, $notification_message );
					}
	
					$from_name = WC()->mailer->get_from_name();
					$from_address = WC()->mailer->get_from_address();
					$headers[] = sprintf( 'From: %s <%s>', $from_name, $from_address );
	
					$response = wp_mail( $to, $subject, $notification_message, $headers );
				}
			}
		} 
	}
	add_action( 'save_post', 'post_published_notification', 99, 1 );
	
	function create_downloads_list( $permalinks = array() ){
	
		$downloads_list = '';
		if ( !empty( $permalinks ) ) {
			
			$downloads_list = '<ul>';
			foreach ( $permalinks as $key => $value ) {
		
				$downloads_list .= sprintf( '<li><a href="%s">Descargar %s</a></li>', $value[ 'download_url' ], $value[ 'name' ] );
			}
			$downloads_list .= '</ul>';
		}
	
		return $downloads_list;
	}
	
	function get_email_format_permalinks( $permalinks ){
	
		if ( empty( $permalinks ) ) return false;
	
		$email_format_permalinks = array();
		foreach ( $permalinks as $key => $info_link ) {
	
			$path_info = pathinfo( $info_link[ 'file' ] );
			if ( !empty( $path_info[ 'extension' ] ) && ( $path_info[ 'extension' ] == 'zip' ) ) {
	
				$email_format_permalinks[ 'plugin_downloads' ][] = array( 'name' => $info_link[ 'name' ], 'download_url' => $info_link[ 'download_url' ] );
			}else{
	
				$email_format_permalinks[ 'documentation_downloads' ][] = array( 'name' => $info_link[ 'name' ], 'download_url' => $info_link[ 'download_url' ] );
			}
		}
	
		return $email_format_permalinks;
	}
	
	// Add allow updates notification field to product meta box
	add_action( 'woocommerce_product_options_general_product_data', 'woo_add_allow_updates_notification_field' );
	function woo_add_allow_updates_notification_field(){
	
	  woocommerce_wp_checkbox( 
	    array( 
	      'id'            => 'updates_notification', 
	      'wrapper_class' => 'show_if_simple show_if_variable', 
	      'label'         => 'Notificar actualizaciones', 
	      'description'   => 'Envía a todos los clientes que hayan comprado este producto, un email de notificación de nueva versión disponible cuando actualizas la ficha de producto.' 
	      )
	    );
	}
	
	add_action( 'add_meta_boxes', 'woo_update_notification_metabox' );
	function woo_update_notification_metabox()
	{
		add_meta_box( 'woo-update-notification-box', 'Mensaje de notificación de la actualización', 'render_woo_update_notification_metabox', 'product', 'normal', 'default' );
	}
	
	function render_woo_update_notification_metabox( $post )
	{
	    	$settings = array(
			'textarea_name' => 'update_notification_message',
			'textarea_rows' => 10,
			'quicktags'     => array( 'buttons' => 'em,strong,link' ),
			'tinymce'       => array(
				'theme_advanced_buttons1' => 'bold,italic,strikethrough,separator,bullist,numlist,separator,blockquote,separator,justifyleft,justifycenter,justifyright,separator,link,unlink,separator,undo,redo,separator',
				'theme_advanced_buttons2' => '',
			),
			'editor_css'    => '<style>#wp-excerpt-editor-container .wp-editor-area{height:175px; width:100%;}</style>'
		);
	
	    	$update_notification_content = get_post_meta( $post->ID, 'update_notification_message', true );
		wp_editor( htmlspecialchars_decode( $update_notification_content ), 'update_notification_message', $settings );
	
		wp_nonce_field( 'woo-update-notification-box-nonce', 'update_notification_nonce' );
	}
	
	add_action( 'save_post', 'woo_update_notification_metabox_save' );
	function woo_update_notification_metabox_save( $post_id ){
	
		// Bail if we're doing an auto save  
	    	if( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return;
	 	
	    	// if our nonce isn't there, or we can't verify it, bail 
	    	if( !isset( $_POST[ 'update_notification_nonce' ] ) || !wp_verify_nonce( $_POST[ 'update_notification_nonce' ], 'woo-update-notification-box-nonce' ) ) return;
	 	
	    	// if our current user can't edit this post, bail  
	    	if( 'product' == $_POST['post_type'] ) {

	    		if( !current_user_can('edit_page', $post_id) ) {

	    			return $post_id;
	      		} else {
					
				$update_notification_message = isset( $_POST[ 'update_notification_message' ] )? $_POST[ 'update_notification_message' ] : '';
				$updates_notification = !empty( $_POST[ 'updates_notification' ] )? 'yes' : 'no';
				update_post_meta( $post_id, 'update_notification_message', $update_notification_message ); 
				update_post_meta( $post_id, 'updates_notification', $updates_notification ); 
	      		}
	    	}
	}
}
Ver más tutoriales de: WooCommerce

Tutoriales relaccionados

¿Necesitas un desarrollo a medida?

Login para aceder

LOGIN
REGISTRO