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
Here is a simple example of how I went about assigning a value to a custom field automatically.
Notes:
+ I used the https://www.advancedcustomfields.com/resources/acf-prepare_field/ prepare_field filter to accomplish this.
+ I set a Rule for the Field Group so that the field only gets displayed to the User *after* the Post is Published. This satisfies the criteria for: “default value couldn’t be changed by that user when creating new posts” (I also included an optional “read only” line of code to prevent any manual editing of the field – readonly can be set conditionally as well)
+ I also used the “field key” within the filter call. You can expose the “key” from the Screen Options tab at the top of the Edit Fields page.
+ Further criteria: Only update if the field doesn’t already have a value, and only update it for a specific User.
Here’s the code to store the IP Address of the User in a custom field on-the-fly (not overly useful, but serves as an example):
<?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_ip_function();
if ( $ip ) {
$field['value'] = $ip;
}
return $field;
}
add_filter('acf/prepare_field/key=field_59d7dc6ac103a', 'my_acf_prepare_field');
// this functions gets the IP Address
function my_get_ip_function() {
if ( !empty( $_SERVER['HTTP_CLIENT_IP'] ) ) {
$ip_address = $_SERVER['HTTP_CLIENT_IP'];
} else if ( !empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) {
$ip_address = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
$ip_address = $_SERVER['REMOTE_ADDR'];
}
return $ip_address;
}
?>
Welcome to the Advanced Custom Fields community forum.
Browse through ideas, snippets of code, questions and answers between fellow ACF users
Helping others is a great way to earn karma, gain badges and help ACF development!
We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Privacy Policy. If you continue to use this site, you consent to our use of cookies.