I’m having a problem with updating the post_date in a custom function I’ve written.
I’m trying to change the “post_date” to my custom “meta_date” value.
Here is the function:
function cfc_reset_postdate( $data, $postarr ) {
// If it is our form has not been submitted, so we dont want to do anything
if(defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return;
if($data['post_type'] == 'scripture-memory') {
$date = get_post_meta( get_the_ID(), 'cfc_date', true );
$date = DateTime::createFromFormat('D - M j, Y', $date);
$date = $date->format('Y-m-d');
$data['post_date'] = $date;
return $data;
}
add_filter( 'wp_insert_post_data', 'cfc_reset_postdate', '10', 2);
I’ve tried linking it to all these filters but none seem to work…
It works, except I have to press the “Update” button twice to change the post_date to match my new meta date.
What am I doing wrong?
A Note: Actions and Filters are not really interchangeable: Filters typically must return the passed data or it’s going to break something.
Building off of what m0r7if3r said,
wp_insert_post_data
is a filter, so you should be modifying the post’s $data and returning it at the end of the function.(Alternatively, you could global the variables you need to alter during an appropriate action, then change it.)
for a tutorial, first read: http://core.trac.wordpress.org/browser/tags/3.3.1/wp-includes/post.php#L2566
Then consider the following (I haven’t tested this but it’s based on your code):
I’ve got a loose implementation for you. Look into the
'wp_insert_post_data'
filter, it is the last filter/action executed that has access to the data being inserted. You should be looking at receiving just the first parameter, which will be the array of data, changing that, then returning it. You will have access to all the post data that is about to be inserted, so if you need to do checks (or, in your caseget_post_meta()
) this would be a good time to do them. This filter executes regardless of whether the post is a new post, or an update…but other than that there aren’t many caveats to it. If you need to look at source, its on line 2567 of/wp-includes/post.php
I know this is question was asked a while ago, but just incase someone was wondering, an easier way of doing this would be:
Check out WordPress Codex