I don’t know how to force this function to run as the last function after all other save things from WP are executed.
This is my current code in my plugin:
add_action( 'save_post', 'do_custom_save' );
function do_custom_save( $post_id ) {
// No auto saves
if( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return;
// make sure the current user can edit the post
if( ! current_user_can( 'edit_post' ) ) return;
// assure the post type
if ( ! get_post_type($post_id) == 'post' ) return;
$latitude = $_POST['rw_company_latitude'];
$longitude = $_POST['rw_company_longitude'];
$zoom = '6';
$lat_lon_zoom = $latitude . ', ' . $longitude . ', ' . $zoom ;
update_post_meta($post_id, 'company_map', $lat_lon_zoom );
}
How to force this code to be executed and saved the mixed variable as the last thing? After all the other saving and updating is done.
Because right now it’s updated ok, but then again rewritten by the value from original map field $_POST[‘company_map’]. I need to somehow tell WP that this function should run as the last function when performing saving/updating post stuff.
How to do that?
add_action
has a priority parameter which is 10 by default, you can increase that to load your function late.Change
add_action( 'save_post', 'do_custom_save' );
to
add_action( 'save_post', 'do_custom_save', 100 );
Now the priority is to set to 100 and will load quite late and will allow other function associated to load before this function is executed.
For more details check the function reference for
add_action
.Maruti Mohantyâs suggestion is not bad, but it will fail. There are many core actions with a higher priority:
wp-admin/menu.php
:wp-includes/admin-bar.php
:wp-includes/canonical.php
wp-includes/class-wp-admin-bar.php
:wp-includes/class-wp-customize-manager.php
:wp-includes/widgets.php
:And plugins and themes can use a higher priority too.
So you have to inspect the current filter or action in
$GLOBALS['wp_filter']
, find the highest key and add something. Be aware, a priority could be a string, because it is an array key:So letâs make a function
get_latest_priority()
as a tool:Use this function lately. Wait until most other code has registered its callback. To do that, hook into your desired action first with a priority
0
, get the highest priority you need, and then register the real callback: