Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Populate ACF Select field with menu names - Use the acf/load_value filter to load values to a Select field. https://www.damiencarbery.com/2022/12/populate-acf-select-field-with-menu-names/
<?php
/*
Plugin Name: Populate ACF Select field with menu names
Plugin URI: https://www.damiencarbery.com/2022/12/populate-acf-select-field-with-menu-names/
Description: Use the acf/load_value filter to load values to a Select field.
Author: Damien Carbery
Version: 0.1
*/
add_filter( 'acf/load_field/type=select', 'dcwd_load_select_values' );
function dcwd_load_select_values( $field ) {
$menus = wp_get_nav_menus();
$field[ 'choices' ] = array();
foreach( $menus as $menu ) {
$field[ 'choices' ][ $menu->term_id ] = $menu->name;
}
return $field;
}
add_filter( 'the_content', 'dcwd_display_menu' );
function dcwd_display_menu( $the_content ) {
if ( ! is_single() ) { return $the_content; }
$menu = get_field( 'menu' );
if ( ! empty( $menu ) ) {
//printf( '<p>Menu: %s</p>', $menu );
return $the_content . wp_nav_menu( array( 'menu' => $menu, 'echo' => false, 'theme_location' => '__no_such_location', 'fallback_cb' => false ) );
}
}
// Add the ACF field group with the select field type.
add_action( 'acf/init', 'dcwd_add_menu_field_group' );
function dcwd_add_menu_field_group() {
if ( function_exists( 'acf_add_local_field_group' ) ) {
acf_add_local_field_group(array(
'key' => 'group_639357e36d7b1',
'title' => 'Menu',
'fields' => array(
array(
'key' => 'field_639357e42606e',
'label' => 'Menu',
'name' => 'menu',
'type' => 'select',
'choices' => array(
'one' => 'One',
),
'return_format' => 'value',
),
),
'location' => array(
array(
array(
'param' => 'post_type',
'operator' => '==',
'value' => 'post',
),
),
),
));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment