Home › Forums › Add-ons › Flexible Content Field › Need to short or write better my code.
I am not good with PHP coding.
I have a Flexible Content field, which is located under Options.
There are lots of rows in this Flexible Content. I do not want to show all rows of this Flexible Content together. Want to show one or two rows based on the post type or category or post ID.
I have separated the rows of Flexible Content like below:
$content_rows = get_field(‘flexible_content’, ‘options’);
$content_specific_row_0 = $content_rows[0];
$content_sub_field_value_0 = $content_specific_row_0[‘content’];
$content_specific_row_1 = $content_rows[1];
$content_sub_field_value_1 = $content_specific_row_1[‘content’];
$content_specific_row_2 = $content_rows[2];
$content_sub_field_value_2 = $content_specific_row_2[‘content’];
$content_specific_row_3 = $content_rows[3];
$content_sub_field_value_3 = $content_specific_row_3[‘content’];
$content_specific_row_4 = $content_rows[4];
$content_sub_field_value_4 = $content_specific_row_4[‘content’];
$content_specific_row_5 = $content_rows[5];
$content_sub_field_value_5 = $content_specific_row_5[‘content’];
$content_specific_row_6 = $content_rows[6];
$content_sub_field_value_6 = $content_specific_row_6[‘content’];
$content_specific_row_7 = $content_rows[7];
$content_sub_field_value_7 = $content_specific_row_7[‘content’];
$content_specific_row_8 = $content_rows[8];
$content_sub_field_value_8 = $content_specific_row_8[‘content’];
$content_specific_row_9 = $content_rows[9];
$content_sub_field_value_9 = $content_specific_row_9[‘content’];
But the problem is that, if I have 100 rows then I need to repeat that code 100 times. Is there any way to short this code? or is there any better way to write that code?
There is likely a better way to do what you are trying to do, but I don’t understand the bigger picture so all I can do it to help you optimize the code that you’ve supplied. For this purpose I would use variable variables.
This code has not been tested
$content_rows = get_field(‘flexible_content’, ‘options’);
for ($i=0; $i<count($content_rows); $i++) {
$row_var = "content_specific_row_{$i};
${$row_var} = $content_rows[$i];
$content_var = "content_sub_field_value_{$i}";
${$content_var} = ${$row_var}['content'];
}
You must be logged in to reply to this topic.
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.