Home › Forums › ACF PRO › Set Publish date to ACF's date field › Reply To: Set Publish date to ACF's date field
This is what I’ve ended with, renamed properly but still, only the first one works, second doesn’t. In short, when a user creates a new post (post type) and selects via acf date field, date, hits publish, publish date should be picked up from the ACF date field and set like that. But this approach doesn’t update for either. However, think makes more sense going with cpt detect. Do note, the code below doesn’t actually work for any as I’ve detecting cpt first, so have to find a workaround for that as well.
function set_date_acf_save_posts( $post_id ) {
$post_type = get_post_type($post_id);
if ($post_type === ‘cpt1’) {
// get new value
$theDate = get_field(‘news_date’, $post_id, false);
$theDate = date_create_from_format(‘Ymd’, $theDate);
$theDate = date_format($theDate, ‘Y-m-d H:i:s’);
$news_post = array(
‘ID’ => $post_id,
‘post_date’ => $theDate,
);
// unhook this function so it doesn’t loop infinitely
remove_action(‘acf/save_post’, ‘ set_date_acf_save_posts’);
// update the post, which calls save_post again
wp_update_post( $news_post );
// re-hook this function
add_action(‘acf/save_post’, ‘ set_date_acf_save_posts’);
}
if ($post_type === ‘cpt2’) {
// get new value
$theDate = get_field(‘dealdate’, $post_id, false);
$theDate = date_create_from_format(‘Ymd’, $theDate);
$theDate = date_format($theDate, ‘Y-m-d H:i:s’);
$deals_post = array(
‘ID’ => $post_id,
‘post_date’ => $theDate,
);
// unhook this function so it doesn’t loop infinitely
remove_action(‘acf/save_post’, ‘ set_date_acf_save_posts’);
// update the post, which calls save_post again
wp_update_post( $deals_post );
// re-hook this function
add_action(‘acf/save_post’, ‘ set_date_acf_save_posts’);
}
}
// run after ACF saves the $_POST[‘acf’] data
add_action(‘acf/save_post’, ‘ set_date_acf_save_posts’, 20);
Welcome to the Advanced Custom Fields community forum.
Browse through ideas, snippets of code, questions and answers between fellow ACF users
Helping others is a great way to earn karma, gain badges and help ACF development!
🚀 This week’s session of ACF Chat Fridays dips into the preliminary results of our first ever user survey. Don’t miss it! https://t.co/3UtvQbDwNm pic.twitter.com/kMwhaJTkZc
— Advanced Custom Fields (@wp_acf) May 9, 2023
© 2023 Advanced Custom Fields.
We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Cookie Policy. If you continue to use this site, you consent to our use of cookies.