Troubles with acf/save_post and WP_Query

I made an accounting system with ACF and CPT, but my client wants to be able to see the balances of each account from the post table in a column and not entering the single of each account.

My problem is that these balances are calculated with a WP_Query that is inside the single and from there is saved in the tables with an update_field. If nobody visits the single that code won’t run and the field is not updated.

I just tried with an acf / save_post but although I managed to update fields in tests defining the variable myself at the time of asking you to calculate it with the query everything goes wrong and does nothing anymore.

To calculate the balance of an account I have to add and subtract all the income, expenses, transfers, purchases and sales linked to that account with an object post field that is where I take the ID for the query.

I have tried an acf / save_post but although I managed to update fields in tests defining the variable myself at the time of asking you to calculate it with the query everything goes wrong and does nothing anymore. Even if I define the variable before to run the query the function is not updating the field at least with the initial value.

To calculate the balance of an account I have to add and subtract all the income, expenses, transfers, purchases and sales linked to that account with an object post field that is where I take the ID for the query.

One of the six query’s

$args = array(
‘posts_per_page’ => -1,
‘post_type’ => ‘inein_ingresos’,
‘meta_query’ => array(
array(
‘key’ => ‘cuenta’,
‘value’ => $CuentaID,
‘compare’ => ‘=’
)
)
);
$tingresos_query = new WP_Query( $args );

if( $tingresos_query->have_posts() ):
$total_ingresos = 0;
while ( $tingresos_query->have_posts() ) : $tingresos_query->the_post();
$total_ingresos += get_field(‘total’);
endwhile;
endif;

wp_reset_query(); // Restore global post data stomped by the_post().

The code that calculate the balances

$total_de_cuenta = 0;
require_once( ‘total-ventas.php’ );
require_once( ‘total-ingresos.php’ );
require_once( ‘total-traspasos-entrantes.php’ );
require_once( ‘total-compras.php’ );
require_once( ‘total-egresos.php’ );
require_once( ‘total-traspasos-salientes.php’ );
$total_de_cuenta = $total_ventas + $total_ingresos + $total_traspasose – $total_compras – $total_egresos – $total_traspasoss;
update_field(‘saldo_actual’, intval($total_de_cuenta));

My save_post function

function actualizador_compras( $post_id ) {

$values = get_fields( $post_id );
$CuentaID = get_field(‘cuenta’);
require_once( ‘calculos-query/bancos/total-cuenta.php’ );
}

add_action(‘acf/save_post’, ‘actualizador_compras’, 15);

Read more here:: Troubles with acf/save_post and WP_Query

Leave a Reply

Your email address will not be published. Required fields are marked *