ochoarobert1 / ccontrol

Simple plugin for Client control, budgeting and invoice. Manage your business operations with ease.
https://robertochoaweb.com/
GNU General Public License v2.0
3 stars 1 forks source link

automatically update Invoice post title based on the 'cliente_factura'+numero_factura+date #11

Open LebToki opened 8 months ago

LebToki commented 8 months ago

//------------------------------------------------------------------------------------ // Function to automatically update Invoice post title based on the 'cliente_factura'+numero_factura+date custom field. //------------------------------------------------------------------------------------ function update_cc_invoice_title_on_save_with_total( $post_id ) { if ( 'cc_invoices' != get_post_type( $post_id ) ) return;

    remove_action('save_post', 'update_cc_invoice_title_on_save_with_total');

    // Get metadata values
    $cliente_factura_id = get_post_meta( $post_id, 'cliente_factura', true );
    $numero_factura = get_post_meta( $post_id, 'numero_factura', true );
    $cliente_factura_name = get_the_title( $cliente_factura_id ); // Fetching the client name
    $items_factura = get_post_meta( $post_id, 'items_factura', true );

    // Calculate total from line items
    $total = 0;
    if (is_array($items_factura)) {
        foreach ($items_factura as $item) {
            $price = isset($item['item_factura_price']) ? floatval($item['item_factura_price']) : 0;
            $qty = isset($item['item_factura_qty']) ? intval($item['item_factura_qty']) : 0;
            $total += $price * $qty;
        }
    }

    $publish_date = get_the_date( 'Y-m-d', $post_id );
    $formatted_total = number_format($total, 2, '.', ','); // Format the total as needed

    $new_title = $cliente_factura_name . ' - Invoice: ' . $numero_factura . ' - Date: ' . $publish_date . ' - Total: ' . $formatted_total;

    // Update the post
    wp_update_post( array(
        'ID'         => $post_id,
        'post_title' => $new_title,
        'post_name'  => sanitize_title($new_title)
    ));

    add_action('save_post', 'update_cc_invoice_title_on_save_with_total');
}
add_action( 'save_post', 'update_cc_invoice_title_on_save_with_total' );
LebToki commented 8 months ago

get the plugin directly from here Github Repo