Last active
October 23, 2024 21:33
-
-
Save RadGH/a1473a24782e93435951ef0f390deb2e to your computer and use it in GitHub Desktop.
ACF: Display custom metabox on an ACF (sub-) options page
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Add sub options page with a custom post id | |
*/ | |
if( function_exists('acf_add_options_page') ) { | |
acf_add_options_sub_page(array( | |
'page_title' => 'CSV Sync', | |
'menu_title' => 'CSV Sync', | |
'parent_slug' => 'users.php', | |
'post_id' => 'aa_ucs', | |
'autoload' => false, | |
)); | |
} | |
/** | |
* Registers a metabox with ACF for a particular screen. You may need to find the screen ID yourself. | |
*/ | |
function aa_ucs_register_acf_metabox() { | |
// Verify the screen ID | |
if ( !acf_is_screen( 'users_page_acf-options-csv-sync' ) ) return; | |
// Add meta box | |
add_meta_box( 'meta-box-id', __( 'My Meta Box', 'textdomain' ), 'aa_ucs_display_acf_metabox', 'acf_options_page', 'normal' ); | |
} | |
add_action( 'acf/input/admin_head', 'aa_ucs_register_acf_metabox', 10 ); | |
/** | |
* Display custom metabox on an ACF options page | |
*/ | |
function aa_ucs_display_acf_metabox() { | |
$text = get_option( 'example-text' ); | |
?> | |
<input type="text" name="exampletext" placeholder="Enter some example text to be saved" value="<?php echo esc_attr($text); ?>"> | |
<?php | |
} | |
/** | |
* Submit metabox form, save the results | |
* | |
* @param $post_id | |
*/ | |
function aa_ucs_save_acf_metabox_fields( $post_id ) { | |
if ( $post_id != 'aa_ucs' ) return; | |
$text = isset($_POST['exampletext']) ? stripslashes($_POST['exampletext']) : false; | |
update_option( 'example-text', $text ); | |
} | |
add_action( 'acf/save_post', 'aa_ucs_save_acf_metabox_fields', 20 ); |
Thanks for this example @RadGH!
For anyone else who may be stuck with acf/save_post
not firing, you need at least 1 real ACF field attached to the options page.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@etomProductions Thanks, I really appreciate that! I'm glad you found this helpful 🙂