I also had some difficulty getting the $field['default_value']
to work in the acf/prepare_field
. @dreiqbik got me on track (thanks!). You can obviously use another filter, but if you need to define the default value when preparing the field, using $field['value']
can imitate the $field['default_value']
.
This will override any selected value though, so you’ll have to filter it yourself. Check if it already has a value set, and if you don’t know if the field allows for null, you should check for that too:
if(!$field['value'] && !$field['allow_null']) {
$field['value'] = 'YOUR DEFAULT VALUE';
}
I know this is a pretty old post, but if anyone else wanted the code to make this happen:
function sevenYearSelect($field) {
$currentYear = date('Y');
// Create choices array
$field['choices'] = array();
// Add blank first selection; remove if unnecessary
$field['choices'][''] = ' ';
// Loop through a range of years and add to field 'choices'. Change range as needed.
foreach(range($currentYear-1, $currentYear+5) as $year) {
$field['choices'][$number] = $year;
}
// Return the field
return $field;
}
add_filter('acf/load_field/key=field_0000000000000', 'sevenYearSelect');
Thanks John. This looks like it could be an ambitious project for my level. But very keen to give it a crack and learn some new things. Thanks for setting me on the right path! I really appreciate it.
Thanks John, the critical error was something else. Have fixed everything with your comments. And it’s now working perfectly. Thank you so much. You’ve been a huge help.
Ah thank you John! I did try that, but I must’ve made another mistake. Turns out it was an easy fix! Thank you very much.
I finally got it! I think I wasn’t declaring my variables clearly enough.
$row = get_field( 'document' );
$first_row = $row[0];
$first_row_file = $first_row[ 'file' ];
if( $first_row_file ) :
$download = '<div>Available!<div>This document is ready for download.</div></div>' ;
echo $download;
else :
$unavailable = '<div>Unavailable!<div>This document isn\'t ready yet. Please check back later.</div></div>' ;
echo $unavailable;
endif;
Now I can add more sophisticated content (like a download button) to display when there is a file to download, and a helpful message when there isn’t.
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 Cookie Policy. If you continue to use this site, you consent to our use of cookies.