I’ve modified your code and moved $ip inside the function. That way the variable is easily accessible from the function itself.
function cptpost() {
if (!empty($_SERVER["HTTP_CLIENT_IP"])) {
$ip = $_SERVER["HTTP_CLIENT_IP"];
} elseif (!empty($_SERVER["HTTP_X_FORWARDED_FOR"])) {
$ip = $_SERVER["HTTP_X_FORWARDED_FOR"];
} else {
$ip = $_SERVER["REMOTE_ADDR"];
}
$dateTime = date("Y/m/d g:i:sa")
//create post object
$userid = get_current_user_id();
$my_post = array(
'post_title' => wp_strip_all_tags($_POST['name']),
'post_content' => "PRODUCT: " . $_POST['name'] . ". PRICE: " . $_POST['price'] . " VAT: " . $_POST['vat'] . " %. IP:".$ip." Date:".$dateTime,
'post_status' => 'publish',
'post_author' => 1,
);
wp_insert_post($my_post);
}
add_action('wp_head', 'cptpost');
Note: I assume your existing code was working for the post insert part. I just rearranged the code to make sure IP is included.