Created
April 2, 2012 22:28
-
-
Save jeremyboggs/2287635 to your computer and use it in GitHub Desktop.
Save custom post metadata in WP
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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/