Updating the database with advanced custom fields

I’m having a real problem with updating a database table using advanced custom fields within a custom post type.

I have a table in the database called ‘wp_company_profiles’ with fields ‘address_1’ and ‘address_2’, and have two advanced custom fields set up with the same values. I am trying to put together a hook that will update the table fields when a particular post in updated.

Read More

Below is the code I am using, but I can’t figure out why it won’t work.

function update_company_profile($post_ID)  {
    global $wpdb;

    if ($parent_id = wp_is_post_revision( $post_id )) $post_ID = $parent_id;

    $address_1 = get_post_meta($post_ID, 'address_1', true);
    $address_2 = get_post_meta($post_ID, 'address_2', true);

    $sql = $wpdb->query("UPDATE wp_company_profiles SET
            address_1 = '{$address_1}',
            address_2 = '{$address_2}',
            WHERE pid = {$post_ID}");

    $wpdb->query($sql);
}

add_action('save_post', 'update_company_profile');

Related posts

1 comment

  1. You’re running the query twice and passing the result of the first query to the second query. Give this a try. You might also consider using the update function from wpdb instead of running an arbitrary query because it doesn’t look like you’re doing any data sanitization or nonce checks. If you do want to query, you should use prepare.

    function update_company_profile($post_ID)  {
        global $wpdb;
    
        if ($parent_id = wp_is_post_revision( $post_id )) $post_ID = $parent_id;
    
        $address_1 = get_post_meta($post_ID, 'address_1', true);
        $address_2 = get_post_meta($post_ID, 'address_2', true);
    
        $sql = $wpdb->prepare("UPDATE wp_company_profiles SET
                address_1 = '%s',
                address_2 = '%s',
                WHERE pid = %d", $address_1, $address_2, $post_ID);
    
        $wpdb->query($sql);
    }
    
    add_action('save_post', 'update_company_profile');
    

Comments are closed.