Skip to content

Instantly share code, notes, and snippets.

@mommaroodles
Created May 26, 2025 21:12
Show Gist options
  • Select an option

  • Save mommaroodles/10ba3dc766aefa0d01b46e3f4029f190 to your computer and use it in GitHub Desktop.

Select an option

Save mommaroodles/10ba3dc766aefa0d01b46e3f4029f190 to your computer and use it in GitHub Desktop.
Fixes the "Attempt to read property name on null" error in WordPress menu management by cleaning up orphaned menu location assignments.
<?php
/**
* Plugin Name: Menu Location Error Fix
* Plugin URI: https://wpdevs.co.za
* Description: Fixes the "Attempt to read property name on null" error in WordPress menu management by cleaning up orphaned menu location assignments.
* Version: 1.0.0
* Author: Melanie Shepherd
* License: MIT
*/
// Prevent direct access
if (!defined('ABSPATH')) {
exit;
}
class MenuLocationErrorFix {
public function __construct() {
add_action('admin_init', array($this, 'cleanup_orphaned_menu_locations'));
add_filter('wp_nav_menu_objects', array($this, 'filter_menu_objects'), 10, 2);
}
/**
* Clean up orphaned menu location assignments
*/
public function cleanup_orphaned_menu_locations() {
$locations = get_theme_mod('nav_menu_locations');
if (!empty($locations)) {
$updated = false;
foreach ($locations as $location => $menu_id) {
if ($menu_id) {
$menu_object = wp_get_nav_menu_object($menu_id);
// If menu doesn't exist, remove the assignment
if (!$menu_object || is_wp_error($menu_object)) {
unset($locations[$location]);
$updated = true;
}
}
}
// Update the theme mod if we removed any invalid assignments
if ($updated) {
set_theme_mod('nav_menu_locations', $locations);
}
}
}
/**
* Filter menu objects to prevent errors
*/
public function filter_menu_objects($items, $args) {
// Additional safety check for menu items
return is_array($items) ? $items : array();
}
}
// Initialize the plugin
new MenuLocationErrorFix();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment