WooCommerce: creare fatture senza plugin

WooCommerce: creare fatture senza plugin

WooCommerce necessita di plugin specifici per generare le fatture degli ordini. Tuttavia una soluzione senza plugin è possibile.

Creiamo un custom post type per le nostre fatture:


add_action( 'init', 'my_invoice_create' );


function my_invoice_create() {
	$labels = array(
		'name'               => _x( 'Fatture', 'post type general name', 'your-plugin-textdomain' ),
		'singular_name'      => _x( 'Fattura', 'post type singular name', 'your-plugin-textdomain' ),
		'menu_name'          => _x( 'Fatture', 'admin menu', 'your-plugin-textdomain' ),
		'name_admin_bar'     => _x( 'Fattura', 'add new on admin bar', 'your-plugin-textdomain' ),
		'add_new'            => _x( 'Nuova', 'fatture', 'your-plugin-textdomain' ),
		'add_new_item'       => __( 'Nuova fattura', 'your-plugin-textdomain' ),
		'new_item'           => __( 'Nuova fattura', 'your-plugin-textdomain' ),
		'edit_item'          => __( 'Modifica fattura', 'your-plugin-textdomain' ),
		'view_item'          => __( 'Visualizza fattura', 'your-plugin-textdomain' ),
		'all_items'          => __( 'Tutte le fatture', 'your-plugin-textdomain' ),
		'search_items'       => __( 'Cerca fattura', 'your-plugin-textdomain' ),
		'parent_item_colon'  => __( 'Fatture genitrici:', 'your-plugin-textdomain' ),
		'not_found'          => __( 'Nessuna fattura trovata.', 'your-plugin-textdomain' ),
		'not_found_in_trash' => __( 'Nessuna fattura trovata nel cestino.', 'your-plugin-textdomain' )
	);

	$args = array(
		'labels'             => $labels,
                'description'        => __( 'Fatture', 'your-plugin-textdomain' ),
		'public'             => true,
		'publicly_queryable' => true,
		'show_ui'            => true,
		'show_in_menu'       => true,
		'query_var'          => true,
		'rewrite'            => array( 'slug' => 'fatture' ),
		'capability_type'    => 'post',
		'has_archive'        => false,
		'hierarchical'       => false,
		'menu_position'      => null,
		'supports'           => array( 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'custom-fields' )
	);

	register_post_type( 'fatture', $args );
}

Registriamo e salviamo i campi per l'inserimento del codice fiscale e della partita IVA:


add_filter( 'woocommerce_checkout_fields' , 'my_invoice_checkout_fields' );

function my_invoice_checkout_fields( $fields ) {
  $fields['billing']['partita_iva'] = array(
        'label'     => __('Partita IVA', 'woocommerce'),
    'placeholder'   => _x('Partita IVA', 'placeholder', 'woocommerce'),
    'required'  => false,
    'class'     => array('form-row-wide'),
    'clear'     => true
     );
     $fields['billing']['codice_fiscale'] = array(
           'label'     => __('Codice fiscale', 'woocommerce'),
       'placeholder'   => _x('Codice fiscale', 'placeholder', 'woocommerce'),
       'required'  => false,
       'class'     => array('form-row-wide'),
       'clear'     => true
        );

     return $fields;
}

function my_invoice_save_extra_checkout_fields( $order_id, $posted ){
    if( isset( $posted['partita_iva'] ) ) {
        update_post_meta( $order_id, '_billing_partita_iva', sanitize_text_field( $posted['partita_iva'] ) );
    }
    if( isset( $posted['codice_fiscale']  ) ) {
        update_post_meta( $order_id, '_billing_codice_fiscale', $posted['codice_fiscale'] );
    }
}
add_action( 'woocommerce_checkout_update_order_meta', 'my_invoice_save_extra_checkout_fields', 10, 2 );

Quando l'ordine è completato, generiamo la fattura salvando i dati dell'utente in custom field associati ad un nuovo custom post type di tipo fattura. Il contenuto del post sarà una tabella con il riepilogo dei prodotti acquistati.


add_action( 'woocommerce_checkout_order_processed', 'my_invoice_make' );

function my_invoice_make( $order_id ) {
  $order = new WC_Order( $order_id );
  $items = $order->get_items();
  $total  = $order->get_formatted_order_total();

  $content = '<table>' . "\n";
  $content .= '<thead>' . "\n";
  $content .= '<tr>' . "\n";
  $content .= '  <th>Prodotto</th>' . "\n";
  $content .= '  <th>Quantità</th>' . "\n";
  $content .= '  <th>Prezzo</th>' . "\n";
  $content .= '  <th>IVA 22%</th>' . "\n";
  $content .= '</tr>' . "\n";
  $content .= '</thead>' . "\n";
  $content .= '<tbody>' . "\n";

  foreach( $items as $item ) {
      $content .= '<tr>' . "\n";
      $content .= '  <td>' . $item['name'] . '</td>' . "\n";
      $content .= '  <td>' . $item['qty'] . '</td>' . "\n";
      $content .= '  <td>&euro; ' . intval( $item['line_total'] ) . '</td>' . "\n";
      $content .= '  <td>&euro; ' . intval( $item['line_tax'] ) . '</td>' . "\n";
      $content .= '</tr>' . "\n";
  }
  $content .= '<tr>' . "\n";
  $content .= '  <td colspan="4" style="text-align: right">' . "\n";
  $content .= '    <strong>Totale:</strong> ' . $total . "\n";
  $content .= '  </td>' . "\n";
  $content .= '</tr>' . "\n";
  $content .= '</tbody>' . "\n";
  $content .= '</table>' . "\n";

  $values = array(
    'nominativo' => get_post_meta( $order->id, '_billing_first_name', true ) . ' ' . get_post_meta( $order->id, '_billing_last_name', true ),
    'ragione_sociale' => get_post_meta( $order->id, '_billing_company', true ),
    'indirizzo' => get_post_meta( $order->id, '_billing_address_1', true ) . "\n" . ' ' . get_post_meta( $order->id, '_billing_postcode', true ) .
                  ' ' . get_post_meta( $order->id, '_billing_city', true ) . ' ' . get_post_meta( $order->id, '_billing_state', true ) . "\n" .
                  ' ' . get_post_meta( $order->id, '_billing_country', true ),
    'codice_fiscale' => get_post_meta( $order->id, '_billing_codice_fiscale', true ),
    'partita_iva' => get_post_meta( $order->id, '_billing_partita_iva', true )
  );

  $pid = wp_insert_post(
      array(
      'post_type' => 'fatture',
      'post_title' => 'Fattura ordine n.' . strval( $order_id ),
      'post_status' => 'publish',
      'post_content' => $content
      )
  );

  if( !is_wp_error( $pid ) ) {
      foreach( $values as $k => $v ) {
          update_post_meta( $pid, $k, $v );
      }
  }
}

A questo punto nel nostro tema possiamo aggiungere il template single-fatture.php in cui creiamo il PDF della fattura con la libreria mPDF solo per gli utenti loggati. Fate riferimento alla documentazione della libreria per aggiungere stili e immagini.


<?php
   require_once( get_template_directory() . '/inc/mpdf/mpdf.php' );
   if( !is_user_logged_in() ) {
       wp_redirect( home_url() );
   } else {
       while( have_posts() ) {
           the_post();
           $mpdf = new mPDF();
           $mpdf->WriteHTML( get_the_content() );
           $mpdf->Output();
       }
   }
?>

Torna su