Support

Account

Home Forums General Issues How to set default custom field value on new posts for a specific user Reply To: How to set default custom field value on new posts for a specific user

  • Ok I apologize for the late reply… what I don’t quite grasp is the function to get the ip adress. Here is the modified code I have so far:

    <?php
    function my_acf_prepare_field( $field ) {
      $field['readonly'] = true; // optionally make the field read-only
      if ( $field['value'] ) { return $field; } // bail if field has a value already
      $for_user = 2;
      $current_user_id = (int)get_current_user_id();
      if ( $current_user_id != $for_user ) { return $field; } // bail if not specified user
      $ip = my_get_field_function();
      if ( $ip ) {
        $field['value'] = $ip;
      }
      return $field;
    }
    add_filter('acf/prepare_field/key=HEREFIELDKEY', 'my_acf_prepare_field');
    
    // this functions gets the custom field value
    function my_get_field_function() {
      if ( !empty( $field] ) ) {
        $field_value = $field;
      } else if ( !empty( 'HEREFIELDVALUE' ) ) {
        $field_value = 'HEREFIELDVALUE';
      } else {
        $field_value = $_SERVER['REMOTE_ADDR'];
      }
      return $field_value;
    }
    ?>

    Where “2” is the user ID,
    HEREFIELDKEY is the field key,
    HEREFIELDVALUE is the field value intended to set for the user.
    Question whats the second “else” for (for the getting the ip adress part)?
    Oh and thanks for taking the time to guide me! I really hope I get to learn more php with this example and not just copy paste the code (though a part of me prefers that). Regards.