Support

Account

Home Forums ACF PRO Auto-populate Custom Post Excerpt with one or multiple Custom Field(s) Reply To: Auto-populate Custom Post Excerpt with one or multiple Custom Field(s)

  • Hi John,

    Thank you for pointing me to the right direction but i actually got it working with the solution below. When i edit the custom field value and just click save, the excerpt gets updated as well.

    Would you still recommend that i use the acf/save_post method?

    function update_custom_post_excerpt_with_acf_field( $post_id ) {
        // Ensure ACF is loaded
        if (function_exists('get_field')) {
            // Check if this is a post of your custom post type and not an autosave.
            if ( get_post_type( $post_id ) === 'watercraft' && ! wp_is_post_autosave( $post_id ) && ! wp_is_post_revision( $post_id ) ) {
                // Get the value of the custom field using ACF's get_field function.
                $custom_field_value = get_field( 'watercraft_stock_number', $post_id );
    
                // Check if the custom field value is not empty.
                if ( ! empty( $custom_field_value ) ) {
                    // Prepare an array to update the post excerpt.
                    $post_data = array(
                        'ID'           => $post_id,
                        'post_excerpt' => $custom_field_value,
                    );
    
                    // Update the post excerpt without triggering an infinite loop.
                    remove_action( 'save_post', 'update_custom_post_excerpt_with_acf_field' );
                    wp_update_post( $post_data );
                    add_action( 'save_post', 'update_custom_post_excerpt_with_acf_field' );
                }
            }
        }
    }
    
    // Hook into the save_post action.
    add_action( 'save_post', 'update_custom_post_excerpt_with_acf_field' );