How check if ACF custom field exist before insert or create CPT

1.2k Views Asked by At

I need to validate if a custom field called family_id exists. If this family_id exists or is already created I need to send a message that it is duplicated and that a new one should be assigned.

NOTE: That id is not the one that wordpress assigns automatically is a custom field of ACF.

This is the custom field image

custom field family_id

And this is the code I have:

add_action( 'rest_api_init', function() {
            /*INSERT SINGLE family*/
        register_rest_route( 'api/v2','insert_family', [
            'methods' => 'POST',
            'callback' => 'insert_family'
        ] );
} );

function insert_family( $data ){

        $parameters = $data->get_params();

        $family = array(
            'post_title' => sanitize_text_field( $parameters['post_title'] ),       
            'post_status' => 'publish',
            'post_type' => 'family',
            'meta_input' => array(
                'featured_family' => sanitize_text_field( $parameters['featured_family'] ),
                'family_id' => sanitize_text_field( $parameters['family_id'] ),
            )
        );

        $family_id_created = wp_insert_post( $family );

        if ( is_wp_error( $family_id_id_created ) ) {       
            wp_die( $family_id_created->get_error_message() );
        } else {        
            return "The family was successfully";
        }
}

Thank you so much

0

There are 0 best solutions below