28th Jan '24
/
0 comments

Conditionally Render ACF Custom Fields in the Post Editor

In the BricksLabs Facebook group a user asked:

Hello! ???? Is it possibile to conditionally show ACF meta boxes based on how many parents a custom post type has? For example, show only if the post being edited has 2 parents.

I attempted to use the filter acf/prepare_field, but without success.

Is there a tutorial or example code available that can guide me in achieving this conditional display? Thanks in advance! ????

ACF has a handy acf/prepare_field filter using which custom fields can be conditionally output when editing posts (can be of any post type).

To render a ACF custom field named “location_specialty” only if the current (location) post has exactly two parents using the acf/prepare_field/name=example_field filter, add this code in

Add the following in child theme‘s functions.php (w/o the opening PHP tag) or a code snippets plugin:

<?php 

add_filter( 'acf/prepare_field/name=location_specialty', function ( $field ) {
	return count( get_post_ancestors( get_the_ID() ) ) === 2 ? $field : false;
} );

Use case: Let’s say you have these location posts:

and you want a “Location Specialty” custom field that’s in a field group attached to the “Location” CPT to only appear when Melbourne (or any other location that has 2 parents similarly) is being edited. This code snippet does the job.

Reference

https://developer.wordpress.org/reference/functions/get_post_ancestors/

Get access to all 626 Bricks code tutorials with BricksLabs Pro

Leave the first comment

 

Related Tutorials..

bricks/posts/merge_query Explained

bricks/posts/merge_query Explained

This short article provides details on Bricks' bricks/posts/merge_query filter. On pages rendered by an archive or search template, secondary queries like the ones used for…
Categories:
Tags:
Pro
ACF Repeater sub field value dynamic data condition in Bricks

ACF Repeater sub field value dynamic data condition in Bricks

This Pro tutorial provides the steps to output an element on single posts (can be of any post type) only if a specified ACF (Pro)…
Modifying ACF Field Value Before It Is Output

Modifying ACF Field Value Before It Is Output

Consider the scenario where a Page has a "Page Fields" field group created with ACF Pro like this: Field name: scientific_coordinators (type Repeater)|__ Sub field…
Categories:
How to hide/remove the Block Element from the Bricks Builder

How to hide/remove the Block Element from the Bricks Builder

Don't like the new Block element in Bricks? Just copy/paste the following code into your child theme's functions.php. By the way, It's a terrible idea…
Categories:
Tags: