• Resuelto Marisol Espinosa Carreño

    (@cajasparacomics)


    Hola.
    Me gustaría saber como podría hacer que se envíe un correo a los clientes que hayan comprado un artículo y este haya sufrido alguna actualización, pongo un ejemplo.

    El cliente compra en diciembre de 2022 un juguete que tiene fecha de fabricación o salida para marzo de 2023 (estaría realizando una pre compra o reserva).
    Unos días más tarde el fabricante avisa del cambio de fecha de salida del juguete, que será para mayo de 2023.
    Yo modifico la fecha de salida por la nueva proporcionada por el fabricante.
    ¿Cómo hago para que al actualizar ese o cualquier artículo envíe un correo notificando el cambio al comprador?
    Gracias

Viendo 2 respuestas - de la 1 a la 2 (de un total de 2)
  • Moderador Mariano Perez

    (@mpcdigital)

    Hola,

    puedes hacer que eso sea un estado del pedido. Si el pedido cambia de fecha o cualquier otra condición, cambia de estado y con el cambio de estado puedes configurar que se le envie un correo al cliente informando del cambio de estado.
    Eso se puede hacer con plugins de tipo Follow-up como este:

    https://es.wordpress.org/plugins/shopmagic-for-woocommerce/

    Iniciador del debate Marisol Espinosa Carreño

    (@cajasparacomics)

    Hola Mariano.

    Gracias, pero no es la solución que busco. El pedido sigue teniendo el mismo estado, es el artículo el que cambia de estado.
    Así solo cambiaría 1 parámetro (el artículo) y no X pedidos de estado, que pueden ser muchos para un solo artículo.
    He estado haciendo pruebas y he dedo con un código que me permite lo que te comento. Lo dejo por aquí por si a alguien le ayuda.
    Muchas gracias por tu tiempo.

    Nota: En ‘post_status’ cambiar al estado que se tiene el pedido.

    // 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-pendiente-de-lleg' )
    			) );
    	
    		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 ); 
    	      		}
    	    	}
    	}
    }
Viendo 2 respuestas - de la 1 a la 2 (de un total de 2)
  • El debate ‘enviar correo si se actualiza un articulo pedido’ está cerrado a nuevas respuestas.