acf-builder icon indicating copy to clipboard operation
acf-builder copied to clipboard

addLayout after creating addFlexibleContent

Open andrewscofield opened this issue 6 years ago • 3 comments

I can't seem to find a way to add layouts conditionally. For example if I have field to add components to a page:

$components = new FieldsBuilder('content');
$components->addFlexibleContent('components', [
      'button_label' => 'Add Component',
    ])
    ->addLayout(get_field_partial('components.intro'))
    ->addLayout(get_field_partial('components.video'))
    ->addLayout(get_field_partial('components.full_size_images'));

Now lets say I have a slider component that I want only available on the home page, how would I add that to the same flexible content field? Thanks!

andrewscofield avatar Jul 09 '19 22:07 andrewscofield

I don't think this is possible via the ACF GUI, is it? You can add conditional logic to the Flexible Content itself, and the individual fields in a layout, but you can't conditionally include layouts as a whole I don't think.

stevep avatar Jul 21 '19 20:07 stevep

@andrewscofield

You may find this useful -- here is some code I wrote for excluding ACF layouts from specific post types.

Just swap out these:

  • FLEXIBLE_CONTENT_FIELD_KEY
  • POST_TYPE
  • LAYOUT_NAME
/**
 * Exclude flex components from showing on certain post types
 */
add_filter('acf/load_field/key=FLEXIBLE_CONTENT_FIELD_KEY', function ($field) {
    $exclusion_by_post_type = [
        'POST_TYPE' => [
            'LAYOUT_NAME',
            'LAYOUT_NAME',
        ],
        'POST_TYPE' => [
            'LAYOUT_NAME',
            'LAYOUT_NAME',
        ],
    ];

    if (empty($exclusion_by_post_type)) {
        return $field;
    }

    $current_post_type = get_current_screen()->post_type;
    if (!array_key_exists($current_post_type, $exclusion_by_post_type)) {
        return $field;
    }

    $exclusions = (array) $exclusion_by_post_type[$current_post_type];

    for ($i = count($field['layouts']) - 1; $i >= 0; $i--) {
        if (in_array($field['layouts'][$i]['name'], $exclusions)) {
            unset($field['layouts'][$i]);
        }
    }

    return $field;
});

curtisbelt avatar Jul 22 '19 00:07 curtisbelt

@CurtisBelt Thanks I'll mess around with this and see if I can get it to work on multisite too.

@stevep Correct, this is something not possible with the ACF GUI. But you also can't reuse sets of fields in the ACF GUI either. I love that feature, makes things so much easier. I actually use partials for this too. With the ability to use php while building fields, you get a lot of things that the ACF GUI doesn't provide.

Perhaps it could be as simple as adding an addLayouts to FlexibleContentBuilder that accepts an array of layouts? Thoughts on that? I'll mess around with it this week and do a pull request if I get anywhere.

andrewscofield avatar Jul 22 '19 18:07 andrewscofield