Users typically manually update Types custom fields in the WordPress admin pages while editing a post or via a front-end Toolset form. However, there may be times when you need to programatically update post content in the database using standard WordPress functions, and, if so, you need to be aware of some limitations.
If using the standard WordPress hooks save_post or save_post_{custom-post-slug} to trigger your code you should be aware that:
- The general save_post action must be used with a priority of at least 30 when used in conjunction with post types registered with Types, or inconsistencies in the updated data may be experienced.
- The targeted save_post_{custom-post-slug} action is not triggered at all for post types registered with Types and should not be used.
An example
In the following example we have a custom post type “Projects”. It has two custom fields: a date field “Deadline” and a checkbox field “Overdue”.
Whenever a Project post is updated we want to compare the “Deadline” with the current date, and if the deadline has already passed, automatically mark the “Overdue” field as checked.
Please note that you need to use the wpcf- prefix for all custom fields created using Types.
You need to put the following code into your theme’s functions.php file.
function is_project_overdue( $post_id, $post ){ if ( 'project' == $post->post_type ) { $deadline = get_post_meta( $post_id, 'wpcf-deadline', true ); $now = time(); if ( !empty($deadline) && $now > $deadline ) { update_post_meta( $post_id, 'wpcf-overdue', 1 ); } } } add_action( 'save_post', 'is_project_overdue', 30, 2 );
We use the save_post action hook to trigger our is_project_overdue function. It uses a priority of 30 and makes two arguments available, $post_id and $post.
After checking that we are updating a post of the required type (project) we get the value of the deadline custom date field and compare this with the current date. If we have reached the deadline, the overdue custom checkbox field is set to 1.
Check how you can add and update Types custom fields via front-end forms without PHP coding.