Support

Account

Home Forums Add-ons Flexible Content Field Programatically removing all flex layouts from a post

Solving

Programatically removing all flex layouts from a post

  • Greetings. I’m attempting to write a function that removes all data from a flex component on a given post and I am struggling. I think part of it may be due to me not completely understanding what a row, sub row, layout, or field is in context to flex content. So lets say that on post #999, we have a flex field called community_flex_components and it has this acf data (json representation for brevity):

    {
      "community_flex_components": [
        {
          "acf_fc_layout": "flex_component_1",
          "headline": "foo"
        },
        {
          "acf_fc_layout": "flex_component_2",
          "subheadline": "bar"
        },
        {
          "acf_fc_layout": "flex_component_3",
          "body": "baz"
        }
      ]
    }

    Which one of the delete_() functions and/or combination of loop(s) would be needed to accomplish the following:

    {
      "community_flex_components": []
    }
  • So for brevity sake, I didn’t want to post every permutation of code that I tried. But taking a second look through them I realized I had some arguments out of order on one and it now seems to work. This will essentially “shift” the first layout (row?) off of the flex component:

    delete_row('community_flex_components', 1, 999)

    So given the warning about running delete_row() inside of have_rows loop, is the following an effective way to properly empty a flex component?

    $length = count(get_field('community_flex_components', 999));
    for ($i = 0; $i < $length; $i++) {
        delete_row('community_flex_components', 1, 999);
    }

    It seems kind of ugly but I’m not immediately clear of any other way to do it. Appreciate any tips or insight.

  • 
    $length = count(get_field('community_flex_components', 999));
    for ($i = $length; $i >= 0; $i--) {
        delete_row('community_flex_components', $i, 999);
    }
    
  • Ah, I see, you handled that.

    Yes, that is the best way to accomplish what you want to do.

Viewing 4 posts - 1 through 4 (of 4 total)

You must be logged in to reply to this topic.