0

I am looking for a SQL query to change the value of a custom field, but not on all posts.

Some posts have in the "post_template" custom field a "temp1" value, and I want to change this value to "temp4". Other values of this custom field must remain.

I searched for the perfect query but nothing I found is working.

Thanks.

1
  • 2
    I'd keep in mind that updating post meta via SQL is highly unusual and usually indicates a very bad code smell ( custom fields are only called custom fields in the GUI, they're called post meta in all the APIs, table names, etc). For this task people usually use a WP CLI command to fetch all posts with that particular meta value and swap it out. As an aside, for performance reasons, if you intend to search and filter on that value, you should switch to terms in a custom taxonomy named post_template instead for a major performance boost
    – Tom J Nowell
    Feb 15, 2019 at 0:05

1 Answer 1

0

If you're looking for raw SQL query, then this should help:

UPDATE <PREFIX>postmeta SET meta_value = 'temp4' WHERE meta_value = 'temp1' AND meta_key = 'post_template'

If you want to run this query from WP, then you can use this:

global $wpdb;
$wpdb->update(
    "{$wpdb->prefix}postmeta",
    array( 'meta_value' => 'temp4' ),
    array( 'meta_key' => 'post_template', 'meta_value' => 'temp1' )
);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.