Skip to content

Instantly share code, notes, and snippets.

@rianrietveld
Created November 22, 2012 07:21
Show Gist options
  • Save rianrietveld/4129805 to your computer and use it in GitHub Desktop.
Save rianrietveld/4129805 to your computer and use it in GitHub Desktop.
Save an extra custom post field in custom post type in WordPress
<?php
/**
* This code saves an extra custom post field with a custom post type to WordPress
* Rian Rietveld - rrwd.nl
* Add this to the functions.php in your WordPress child theme
*
* Adding the priority 20 for the add_action to save_post is !important, otherwise it won't work
*/
function rrwd_save_cpf_with_ctp ( $post_id, $post ) {
// thanks to mathsmith on http://wordpress.stackexchange.com/questions/5688/custom-post-type-edit-publish-hook
// prefix_name_cpf is the name of the custom post field
// prefix_name_cpt is the name of the custom post type
// Make sure the post obj is present and complete. If not, bail.
if(!is_object($post) || !isset($post->post_type)) {
return;
}
switch($post->post_type) { // Do different things based on the post type
case "prefix_name_cpt":
if ( is_admin() && ( get_field( 'prefix_name_cpf', $post_id ) ) ) {
// do not save if this is an auto save routine
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return $post_id;
// get the data from the cpf get_field is functionused by the WordPress plugin Advanced Custion Fields by Elliot Condon http://www.advancedcustomfields.com/
$prefix_name_cpf = get_field( 'prefix_name_cpf', $post_id );
// for a regular WordPress call use
// $prefix_name_cpf = get_post_meta($post_id, 'prefix_name_cpf', true);
// do stuff with this variable
$prefix_name_extra_cpf = some_function( $prefix_name_cpf );
// update or add the new cistom post field in the database
add_post_meta( $post_id, '_prefix_name_extra_cpf', $prefix_name_extra_cpf, true )
or update_post_meta( $post_id, '_prefix_name_extra_cpf', $prefix_name_extra_cpf );
}
break;
default:
break;
}
} // end rrwd_save_cpf_with_ctp
add_action( 'save_post', 'rrwd_save_cpf_with_ctp', 20, 2 ); // priority 20 is !IMPORTANT!
function some_function($extra_var) {
// do some stuff here
return $new_var;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment