Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I've searched around a bit, and I'm having trouble finding an answer to this question. What I'm trying to do is automatically fill a custom field when a post (custom post type) is updated or published. Ideally the completed script will call out to an API and fill the custom field with the resulting information whenever a post is created or updated. For right now though, I'm just trying to automatically fill my custom field with a simple string for testing. Here's my code:

add_action( 'save_post', 'update_tmv' );
function update_tmv($postid) {
    if ( !wp_is_post_revision( $postid ) && get_post_type( $postid ) == 'inventory') {
        $field_name = 'market_value';
        add_post_meta($postid, $field_name, 'TEST_STRING', true);    
    }
}

I've used this page as reference: http://www.wpbeginner.com/wp-tutorials/how-to-add-custom-fields-automatically-on-post-publish-in-wordpress/ but unfortunately it's not working. When I publish or save a post the 'market_value' custom field continues to be empty (also, I'm using Advanced Custom Fields to create the custom fields). Any ideas? Thanks!

share|improve this question
    
Was the custom field you're trying to manipulate added via Advanced Custom Field plugin? –  RRikesh May 28 '13 at 5:28

1 Answer 1

up vote 1 down vote accepted

See add_meta_box which has a lot of demo code for working with meta fields. Here is the most relevant part for you:

/* Do something with the data entered */
add_action( 'save_post', 'myplugin_save_postdata' );

/* When the post is saved, saves our custom data */
function myplugin_save_postdata( $post_id ) {

  // First we need to check if the current user is authorised to do this action. 
  if ( 'page' == $_POST['post_type'] ) {
    if ( ! current_user_can( 'edit_page', $post_id ) )
        return;
  } else {
    if ( ! current_user_can( 'edit_post', $post_id ) )
        return;
  }

  $mydata = 'something'; // Do something with $mydata 

  update_post_meta( $post_id, '_my_meta_value_key', $mydata );
}
share|improve this answer
    
Wow! Worked perfectly the first time! I just plugged my values in, and it seems to be working great. Thanks so much, Matthew. –  DEUTSCHWULF May 28 '13 at 15:50
    
*I'd upvote, but I'm afraid I can't quite do that yet. –  DEUTSCHWULF May 28 '13 at 15:51

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.