post meta - SQL query to change the value of a Custom Field

admin2025-06-03  4

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.

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.

Share Improve this question edited Feb 15, 2019 at 7:00 Krzysiek Dróżdż 25.6k9 gold badges53 silver badges74 bronze badges asked Feb 14, 2019 at 23:52 jnrmyjnrmy 215 bronze badges 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 Commented Feb 15, 2019 at 0:05
Add a comment  | 

1 Answer 1

Reset to default 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' )
);
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1748905031a314693.html

最新回复(0)