Skip to content

Instantly share code, notes, and snippets.

@mlbd
Last active July 21, 2023 13:25
Show Gist options
  • Save mlbd/a916887cdcb74d37444b34b9371143a4 to your computer and use it in GitHub Desktop.
Save mlbd/a916887cdcb74d37444b34b9371143a4 to your computer and use it in GitHub Desktop.
Programmatically create wp nav menu from external json file
/**
* Registers a wp nav menu Programmatically.
*
* @link https://codex.wordpress.org/Function_Reference/wp_get_nav_menu_object
* @link https://codex.wordpress.org/Function_Reference/wp_create_nav_menu
* @link https://developer.wordpress.org/reference/functions/wp_update_nav_menu_item/
* @link https://developer.wordpress.org/reference/functions/wp_remote_get/
* @link https://codex.wordpress.org/Function_API/wp_remote_retrieve_body
*
* @since 1.0
*/
function createProgrammaticallyWPNav() {
$menu_name = 'Programmatically Create Menu';
$menu_location = 'primary'; // menu theme location
/**
* Fetching data from external using WordPress function.
*
* But if you wish to use CURL or other php function to retrieve external data that's also cool :)
*
*/
$request = wp_remote_get( 'https://api.binameer.com/v1/visa/freevisacountry?reqtype=menu&fbclid=IwAR3IcMqhVKj1Ng3694CqmvlnHvMQJYN6hQMV-ZtsvDFjL7gInwn6smVT68g' );
if( is_wp_error( $request ) )
return false;
$body = wp_remote_retrieve_body( $request );
$get_data = json_decode( $body );
if( empty( $get_data ) || !isset($get_data->data->attributes) )
return false;
// Check if the menu exists
$menu_exists = wp_get_nav_menu_object( $menu_name );
// If it doesn't exist, let's create it.
if( !$menu_exists){
// first create nav menu
$menu_id = wp_create_nav_menu($menu_name);
// then add item into newly-created menu
foreach( $get_data->data->attributes as $item ) {
wp_update_nav_menu_item($menu_id, 0, array(
'menu-item-title' => __($item->cntr_name),
'menu-item-classes' => 'cm-item-' . $item->cntr_code,
'menu-item-url' => home_url( '/' ), // or uses "#" for blank url
'menu-item-status' => 'publish'));
}
/* NOTE */ // if you don't want to assign automaticlly then ignore next step by comment out it.
// Grab the theme locations and assign our newly-created menu
// to the BuddyPress menu location.
if( !has_nav_menu( $menu_location ) ){
$locations = get_theme_mod('nav_menu_locations');
$locations[$menu_location] = $menu_id;
set_theme_mod( 'nav_menu_locations', $locations );
}
}
}
add_action( 'load-nav-menus.php', 'createProgrammaticallyWPNav' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment