Skip to content

Instantly share code, notes, and snippets.

@sethrubenstein
Forked from raideus/acf-auto-export.php
Last active May 19, 2016 03:31
Show Gist options
  • Save sethrubenstein/7089852 to your computer and use it in GitHub Desktop.
Save sethrubenstein/7089852 to your computer and use it in GitHub Desktop.
Changed get_template_directory to get_stylesheet_directory to facilitate child themes
<?php
/**
* Automated PHP export for Advanced Custom Fields
*
* Export is initiated whenever an admin publishes a new field group
* or saves changes to an existing field group.
*
* Place this code in your theme's functions.php file.
*
*/
add_action('admin_head-post.php', 'my_acf_export');
function my_acf_export() {
global $acf;
// IMPORTANT:
// Enter the absolute path to the file you want to export into:
$file = get_stylesheet_directory().'/inc/fields.php';
// Only continue if we're saving a field group
if ( empty($_GET['message']) || ($_GET['message'] != '1' && $_GET['message'] != '6') ) {
return;
}
$fields = array();
$fields = get_posts(array(
'numberposts' => -1,
'post_type' => 'acf',
'orderby' => 'menu_order title',
'order' => 'asc',
));
if($fields)
{
$output = '
if(function_exists("register_field_group"))
{';
foreach($fields as $field)
{
$var = array(
'id' => uniqid(),
'title' => get_the_title($field->ID),
'fields' => $acf->get_acf_fields($field->ID),
'location' => $acf->get_acf_location($field->ID),
'options' => $acf->get_acf_options($field->ID),
'menu_order' => $field->menu_order,
);
$html = var_export($var, true);
// change double spaces to tabs
$html = str_replace(" ", "\t", $html);
// add extra tab at start of each line
$html = str_replace("\n", "\n\t", $html);
// remove excess space from beginning of arrays
$html = str_replace("array (", "array(", $html);
$output .= '
register_field_group('.$html.'); ';
}
$output .= '
}
';
}
else
{
$output = __('No field groups were selected','acf');
}
if (is_writable($file)) {
file_put_contents($file, $output);
define('ACF_EXPORT_FILE', $file);
add_action('admin_notices', 'my_acf_export_success');
} else {
add_action('admin_notices', 'my_acf_export_fail');
}
}
/**
* Notice to display when export is completed successfully
*/
function my_acf_export_success( $file = '' ) {
if (defined('ACF_EXPORT_FILE')){
$destination = ' to <strong>'.ACF_EXPORT_FILE.'</strong>';
} else {
$destination = '';
}
echo '<div class="updated"><p>All fields successfully exported'.$destination.'.</p></div>';
}
/**
* Error message to display when export fails (file not writable)
*/
function my_acf_export_fail( $file = '' ) {
echo '<div class="error"><p><strong>Automated Export Error:</strong> The export file you\'ve specified is not writeable.</p></div>';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment