Last active
December 14, 2015 21:09
-
-
Save AlphaGit/5149216 to your computer and use it in GitHub Desktop.
Adding a custom attribute to Wordpress menu items (Themes -> Appearance -> Menus -> Item edition).
Extracted from https://github.com/AlphaGit/alphasmanifesto/blob/master/custom_menu_setup.php
This file contains hidden or 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 | |
// retrieve menu item custom url attribute when a | |
add_filter( 'wp_setup_nav_menu_item', 'alphasmanifesto_setup_nav_menu_item' ); | |
function alphasmanifesto_setup_nav_menu_item($menu_item) { | |
$attrName = 'image_url'; // property name | |
$genericProperty = "alphasmanifesto_menu_item_$attrName"; // unique property name -- avoid colliding with other plugins/themes | |
// get it from the database with its id, set it to the menu item | |
$menu_item->image_url = get_post_meta($menu_item->ID, $genericProperty, true); | |
// return the modified menu item | |
return $menu_item; | |
} | |
// save menu item custom url attribute | |
add_action( 'wp_update_nav_menu_item', 'alphasmanifesto_update_nav_menu_item', 10, 3 ); | |
function alphasmanifesto_update_nav_menu_item($menu_id, $menu_item_id, $args) { | |
$attrName = 'image_url'; // property name | |
$genericProperty = "alphasmanifesto_menu_item_$attrName"; // unique property name -- avoid colliding with other plugins/themes | |
// if the value is being submitted through post (being saved) | |
if ( isset( $_POST[ "menu-item-image-url" ] ) ) { | |
// retrieve the one bound to this item ID (see the form generation) | |
$value = $_POST[ "menu-item-image-url" ][$menu_item_id]; | |
// save the value to the database with the item id | |
update_post_meta( $menu_item_id, $genericProperty, $value ); | |
} else { | |
// if its not being provided, delete it from the database, for that item id | |
delete_post_meta( $menu_item_id, $genericProperty ); | |
} | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment