Skip to content

Instantly share code, notes, and snippets.

@jeremyboggs
Created April 2, 2012 22:28
Show Gist options
  • Save jeremyboggs/2287635 to your computer and use it in GitHub Desktop.
Save jeremyboggs/2287635 to your computer and use it in GitHub Desktop.
Save custom post metadata in WP
<?php
/**
* Save custom post metadata fields in WordPress.
*/
function my_custom_save_post(){
global $post;
// Populate this array with the names of your fields.
// Should match ID/name attributes in your form.
$customFields = array('field_name_one','field_name_two','field_name_three');
// Loop through each field, check if it exists in the $_POST when saving the post, then
// use update_post_meta() to update the metadata field for the blog post.
foreach ($customFields as $field) {
if (array_key_exists($field, $_POST)) {
update_post_meta($post->ID, $field, $_POST[$field]);
}
}
}
add_action( 'save_post', 'my_custom_save_post');
@jakemayfield
Copy link

Anyone using this should sanitize the $_POST data, which is not currently being done here.

You can learn more about data sanitization here:
https://developer.wordpress.org/themes/theme-security/data-sanitization-escaping/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment