Skip to content

Instantly share code, notes, and snippets.

@drrobotnik
Created June 27, 2014 20:15
Show Gist options
  • Save drrobotnik/5bbef57d55ef7ac9308f to your computer and use it in GitHub Desktop.
Save drrobotnik/5bbef57d55ef7ac9308f to your computer and use it in GitHub Desktop.
functions.php

###Concept ACF Flexible content field is very handy for creating many optional layouts. Sometimes we want to restrict an optional layout to be used only one time, and sometimes in a specific location. This helper function allows you to control the flexibility, but enforce the structure cleanly as if you were using WP's get_template_part. See page.php for examples.

###File Structure Put the layout files inside of /themes/themename/layouts/acf/layout-file.php

###Naming optional field name: grid_slider, will look for file: grid-slider.php

function cv_acf_optional_template_parts( $slug = 'layouts/acf/', $names = array(''), $label = 'optional_layouts', $post_id = null ) {
include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
if (is_plugin_active('advanced-custom-fields/acf.php') ) {
$results = array();
while( has_sub_field( $label, $post_id ) ) {
foreach ( $names as $field ) {
if ( $field == get_row_layout() ) {
$results[] = $field;
$template = str_replace('_', '-', $field);
get_template_part( 'layouts/acf/' . $template );
}
}
}
return $results;
}
}
<?php get_header(); the_post();
// If the header gallery is used, it should always be at the top
$header_gallery = cv_acf_optional_template_parts( 'layouts/acf/', array( 'header_gallery' ), 'optional_layouts' );
if( empty($header_gallery) ){
get_template_part( 'layouts/acf/header-image' );
}
// Intro message should always be directly below the header gallery
cv_acf_optional_template_parts( 'layouts/acf/', array( 'intro_message' ), 'optional_layouts' );
?>
<div class="container">
<div class="row">
<div class="col-sm-12">
<?php get_template_part( 'content', 'page' ); ?>
</div>
</div>
</div>
<?php
# The following layouts should be flexible enough to allow the user to define their order.
cv_acf_optional_template_parts( 'layouts/acf/', array( 'info_columns', 'secondary_content', 'visual_divider', 'block_links' ), 'optional_layouts' );
# Grid Slider should always be at the bottom.
cv_acf_optional_template_parts( 'layouts/acf/', array( 'grid_slider' ), 'optional_layouts' );
get_footer();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment