How to update a CPT with data from an API

20 Views Asked by At

I have a CPT "vehicles". It has a number of meta fields, one of which is "registration".

I also have access to an API which allows me to request vehicle data based on a registration number.

I had been thinking I could fetch data from the API to add to a vehicle in the "save_post" hook. That is, get the data then add it to the various meta fields with update_post_meta(). I played with some code to test out my logic but it's giving me problems. So I'm thinking there has to be a better way to go about this?

In my testing, I just tried to update one meta field with a static value. Just to test the concept. I have the code email me with the data. However, it's sending me 2 emails each time. One with the data, and one where the data is blank.

So, I assume this is not the way to go about fetching my API data to actually update each vehicle once the registration number has been added - not if I can't get this simple test to work.

Where am I going wrong? What should I be doing?

function update_vehicle_meta($post_id) {
    // Check if the post type is 'vehicles' to ensure it only affects your custom post type
    if (get_post_type($post_id) === 'vehicles') {
        
        // Check if the save action is an autosave or a revision
        if (wp_is_post_autosave($post_id) || wp_is_post_revision($post_id)) {
            return;
        }
        
        // Check if the user has permission to edit the post
        if (current_user_can('edit_post', $post_id)) {
            
            // Get the value of the 'exterior' field from the POST data
            $exterior = sanitize_text_field($_POST['exterior']) . "_Updated";    
            
            $subject = 'A vehicle has been updated';
            $message = "A vehicle has been updated:\n\n";
            $message .= $_POST['registration'] . ": " . $_POST['exterior'];
    
            // Send email to admin.
            wp_mail( 'my email address', $subject, $message );

            // Update the 'exterior' field for the vehicle
            update_post_meta($post_id, "exterior", $exterior);
        }
    }

}


// Hook into the save_post action to trigger the function when a vehicle is published or updated
add_action('save_post', 'update_vehicle_meta', 10, 3);
0

There are 0 best solutions below