update_post_meta() This is a WordPress function used to update custom fields for articles or pages; it is also known as "metadata." Its function prototype is as follows:
update_post_meta( int $post_id, string $meta_key, mixed $meta_value, mixed $prev_value = '' )Parameter description:
$post_idRequired: The ID of the article or page.$meta_keyRequired. Name of the custom field.$meta_valueRequired. Value for the custom field.$prev_valueOptional. Used to check whether the specified value already exists. If specified, this condition is met only when the value of the custom field equals$prev_valueIt will only be updated when needed.
Call update_post_meta() The function can update the custom field data for a specific article or page. For example, if an article or page contains a custom field named "author," you can use the following code to update its value:
update_post_meta( get_the_ID(), 'author', 'John Doe' );In the above code,get_the_ID() The first parameter is used to retrieve the ID of the current article or page; the second parameter is the name of the custom field; the third parameter is the value to be updated.
Please note that,update_post_meta() The function searches for custom fields based on the custom field name and the article/page ID; if a match is found, its value is updated; if no match is found, a new custom field is created.
If you need to update a custom field but must first check whether that field already exists and whether its current value equals a specific value, you can pass this information as the fourth parameter to the function. $prev_valueFor example, the following code updates the custom field "author" to "John Doe" only when its current value is "Jack":
update_post_meta( get_the_ID(), 'author', 'John Doe', 'Jack' );If the custom field name does not exist, no changes will be made, and the function will return `false`. If the custom field value has not changed, the custom field will not be updated, and the function will return `false`. If the update is successful, the function will return `true`.
Please note that due to WordPress caching, if you update the value of a custom field in your code but the new value does not appear on the page, you may try using the following approach: wp_cache_flush() Clears the cache.