I need to update all meta keys in the postmeta table that have a value other than 0, to the value of 0.
I tried this.. no love (though I cannot figure out why….):
$status = $wpdb->query("UPDATE {$wpdb->prefix}postmeta SET meta_value=0 WHERE meta_key = _wti_like_count AND meta_value <> '0'");
I’m on this concept, but how to say “!0” NOT 0 in the key list?
$wpdb->update('wp_postmeta', array('_wti_like_count' => '0'), array('_wti_like_count' => '0'));
Thanks a ton!
UPDATE: I fixed my $wpdb->query
as follows and it works:
$status = $wpdb->query("UPDATE {$wpdb->prefix}postmeta SET meta_value='0' WHERE meta_key = '_wti_like_count' AND meta_value <> '0'");
However, I would still like to know if there is a way to pass a key pair array to the WHERE
parameter of $wpdb->update
and request a !=
value.
The
$wpdb
class propertiesYou can use all the default WordPress tables like this:
$GLOBALS['wpdb']->postmeta
so no need to use
prefix
, etc.meta_query
As you can see from the Custom field parameter documentation, there’s nothing like the
<>
(or in other words: “not equal to”) operator. The equivalent operator in WP should be!=
(human words: “not is”) orNOT LIKE
.So simply do something along the following lines:
This would query all your posts with this meta value. What makes me wonder is why you got a
string
as aninteger
. I wouldn’t do that, especially not if I use a counter. See what I commented out: Thetype
, which would allow you – later on – much more specific queries.Update the meta entries
Then simply loop through them and update the values.
It does not look like it is possible to use != in the where. Here is the relevant code from the
update()
method:The
$wheres[]
line is telling. It shows only=
is ever used. That array is used later:In your case, the query could have worked without checking for the value not being
0
. The result would have been the same (though more rows would have been affected), but it looks like this method is limited to only=
in the WHERE clauses.