Support

Account

Home Forums General Issues Save total CPT count to ACF field Reply To: Save total CPT count to ACF field

  • Thought id update this thread as I ended up working direct with another developer on this.

    He wrote a custom function, which relies on a new ACF field that stores the count data.

    I hope it helps somebody else!

    function generateInvoiceId($post_id) {
    	// bail early if no ACF data
        if(empty($_POST['acf'])){
            return;
        }
    
    	/***************************
    	Structure of settings array.
    
    	array(
    		[post_type]=>[array(
    			[id_field_name]=>[value]
    			[starting_id]=>[value]
    		)
    	)
    
    	The 'id_field_name' is the name of the ID field that you created in admin.
    	They MUST be unique so the post type can be determined correctly.
    
    	*************************/
    
    	$settings=array(
    		'exporting'=>array(
    			'id_field_name'=>'import_id',
    			'starting_id'=>1
    		),
    		'acquisition'=>array(
    			'id_field_name'=>'export_id',
    			'starting_id'=>1
    		)
    	);
    
    	$id_field_form=null;
    	$id_field_name=null;
    	$post_type=null;
    
    	//find which form field is the relavant id field and use it to determine which settings to use
    	foreach($_POST['acf'] as $form_name => $field){
    		$field_data=get_field_object($form_name);
    
    		foreach($settings as $post_type_setting => $setting){
    			if($field_data['name']===$setting['id_field_name']){
    				$id_field_form=$form_name;
    				$id_field_name=$setting['id_field_name'];
    				$post_type=$post_type_setting;
    				break 2;
    			}
    		}
    	}
    
    	if($id_field_form===null||$id_field_name===null||$post_type===null||is_numeric($_POST['acf'][$id_field_form])){
    		//not the right post type or this is an update
    		return;
    	}
    
    	//new post save - get last id and increment;
    	$last_post=get_posts(array(
    		'posts_per_page'   => 1,
    		'offset'           => 1,
    		'orderby'          => 'date',
    		'order'            => 'DESC',
    		'post_type'        => $post_type
    	));
    
    	$generated_id=null;
    
    	if(count($last_post)>0){
    		//Posts have already been created of this type. Retrieve last post id and increment
    		$last_post=get_fields(array_pop($last_post));
    		$last_id=$last_post[$id_field_name];
    		$generated_id=$last_id+1;
    	}
    	else{
    		//This is the first post of the this type. ID will be set to the starting id.
    		$generated_id=$settings[$post_type]['starting_id'];
    	}
    
    	//set the new id to the form data and exit
    	$_POST['acf'][$id_field_form]=$generated_id;
    	return true;
    }
    
    add_action('acf/save_post', 'generateInvoiceId', 1);