Hello!
I’ve hit a wall in my abilities to work out how I can dynamically preset the value of a Post Object within an acf_form. The scenario I’m working with is as follows:
Product Page:
From here a user can click a link which will take him to a general “review” page where the user can write about the product. I’m passing the ID for the product page as a query string which I pick up from the review page.
Review Page:
This page has an acf_form with a Post Object field and a WYSIWYG field. The Post Object field allows the user to select a product directly from here and the text area is the general review input.
Challenge:
The Post Object field works just fine on its own, but I’m not sure about the best way to preset the field to the product ID when the user comes from a product page. Below are some snippets to help illustrate the issue.
// On the review page I grab the URL parameter 'spirit'
// ?spirit=2128
if (isset($_GET['spirit'])) {
$spirit_id = $_GET['spirit'];
// NOW, HOW TO I GET THIS ID INTO THE PREPARE FIELD FUNCTION?
}
// In functions.php I've added this to be able to prepare the field before it's rendered on the page
function my_acf_prepare_field( $field ) {
// This works, but the Post Object needs to be dynamic
$field['value'] = get_post( 2128 );
return $field;
}
add_filter('acf/prepare_field/key=field_57ed83fe45f49', 'my_acf_prepare_field');
As I mentioned above, I’m not sure if this is even the right way to go about solving this, so would love to get some insights on this challenge.
Thanks!
The field value in ACF for an post object field is simply the post ID. If you are only allowing 1 selection then it is a single value and if the field allows multiple then it is an array of post IDs. These values need to be integers.
I am not 100% sure that prepare_value will work but it should look something like this
function my_acf_prepare_field( $field ) {
if (isset($_GET['spirit'])) {
$field['value'] = intval($_GET['spirit']);
}
return $field;
}
add_filter('acf/prepare_field/key=field_57ed83fe45f49', 'my_acf_prepare_field');
If prepare field does not work you could try acf/load_value instead https://www.advancedcustomfields.com/resources/acfload_value/
The topic ‘Dynamically Prepare Field (ACF PRO)’ is closed to new replies.
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.