I am trying to create a field called "numero" as an auto increment field with advanced custom fields.
This function with WP_Query returns the last inserted "numero".
function get_last_numero(){
$args = array(
'posts_per_page'=> 1,
'post_type' => 'sep_doc',
'post_status' => 'publish, draft, trash',
'meta_key' => 'numero',
'orderby' => 'meta_value_num',
'order' => 'DESC'
);
$the_query = new WP_Query( $args );
if ( $the_query->have_posts() ) {
while ( $the_query->have_posts() ) {
$the_query->the_post();
$pid = get_the_ID();
$numero = get_field(numero,$pid);
}
}
wp_reset_postdata();
return (int)$numero;
} And this sets the default value in ACF "numero" field as whatever I put in the $numero_id variable;
$numero_id = get_last_numero() + 1; // tested with static value 123456 - IT's WORKING
add_filter('acf/load_field/name=numero', function($field) use ($numero_id) {
$field['default_value'] = $numero_id;
return $field;
});
Static values and all other functions like get_the_ID() works just fine. But when I put get_last_numero() it crashes the site with error 500.
I believe the reason as I am somehow calling "numero" inside "numero", Can anyone suggest any solutions or workaround to this.
Edit: used a solution like this-
var num = <?php echo get_last_numero(); ?>;
$("#acf-post-field_606b65932d135").val(num+1).prop('readonly',true);