Skip to content

Instantly share code, notes, and snippets.

@luclemo
Last active October 17, 2018 14:43
Show Gist options
  • Save luclemo/4de6f9a7322e1dc4386888c10e5aeecb to your computer and use it in GitHub Desktop.
Save luclemo/4de6f9a7322e1dc4386888c10e5aeecb to your computer and use it in GitHub Desktop.
Get Sub Field From ACF’s Flexible Content Field #wordpress #ACF
<?php
/*
* Get a sub field from within a layout of a flexible content field on a specific page
* @param string $flexFieldName The flexible content field name
* @param string $flexFieldLayoutName The flexible content's layout name
* @param string $flexFieldLayoutField The FCs layout's sub field name
* @return string If exists, then returns the value of the layout's sub field. If not, then it returns a message.
*/
function getFlexFieldByPageID($flexFieldName, $flexFieldLayoutName, $flexFieldLayoutField, $pageID=null){
$pageID = $pageID? $pageID : get_the_ID();
// check if the flexible content field has rows of data on the provided page
if(have_rows($flexFieldName, $pageID)){
// loop through the rows of data of the flexible content field
while(have_rows($flexFieldName,$pageID)){ the_row();
if(get_row_layout() == $flexFieldLayoutName){
return get_sub_field($flexFieldLayoutField);
}else{
return "No layout";
}//end if
}//end while
}else{
return "No data";
}//end if
}
/*
*
* Usage Example:
* Get the address and city values from a “contact_info” layout that is located on the contact page.
*
*/
$contactPageID = 123;
$address = getFlexFieldByPageID('modules', 'contact_info', 'contact_info_address', $contactPageID);
$city = getFlexFieldByPageID('modules', 'contact_info', 'contact_info_city', $contactPageID);
/*
* Source: http://rarespud.com/get-sub-field-acfs-flexible-content-field/
*/
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment