Support

Account

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);