I am using WordPress and I am using a custom field that has the name ecpt_carprice
for each post I am publishing, the field is saved in wp_postmeta
the same as the attached image:

Some of my cars (posts) do not have a meta key ecpt_carprice
.
Can you provide me with any means (WordPress/PHP or SQL query) to store for every post without the meta entry a new entry with value 0?
I have this code but I don’t know how to use it
if ( has_term( '', 'car_brand' )) {
//check if the meta field has a value
$meta_values = get_post_meta($post->ID, 'ecpt_carprice', true);
if(empty($meta_values)){
//add a default value
add_post_meta($post->ID, 'ecpt_carprice', '0');
}
}
If you want to and only need to do what @tf suggested, what is just to take care of displaying a 0 if no value is present, you can construct a function to do so like this:
function wpse121165_return_carprice() {
$ecpt_carprice = get_post_meta($post->ID, 'ecpt_carprice', true);
if(! empty( $ecpt_carprice ) ){
return $ecpt_carprice;
} else {
return 0;
}
}
Use the function like this: echo wpse121165_return_carprice();
If you really need to update your database, you have to do this another way. Below code should give you an insight on how to do it:
function wpse121165_update_carprice_meta() {
// args to query for your key
$args = array(
'post_type' => 'your_post_type',
'meta_query' => array(
'relation' => 'OR',
array(
'key' => 'ecpt_carprice',
'value' => 'bogus', // you have to pass a value
'compare' => 'NOT EXISTS'
),
array(
'key' => 'ecpt_carprice',
'value' => ''
)
),
'fields' => 'ids'
);
// perform the query to get back an array of ids
$not_exist_or_empty_ids = new WP_Query( $args );
foreach ( $not_exist_or_empty_ids as $id ) {
update_post_meta($id, 'ecpt_carprice', '0');
}
}
Use the function like this: wpse121165_update_carprice_meta();
. If you put this in you functions.php
and perform your meta update on the database, make sure to disable it afterwards and not to call it over and over again.