Site icon WP Smith

How to Get WordPress's Custom Menu Description

So recently, someone wanted to use menu descriptions as a tagline of sorts for a variety of pages, categories, archives, etc. instead of using basic metaboxes on pages (since this would also apply to category pages, etc.). So I wrote up a simple function that I believe may be helpful for others. So here is the code. To use, simply copy the function to your functions.php file and then use the function wherever you'd like.

[php]<?php
function wps_get_menu_description( $args = array() ) {
global $post;

// Default
$defaults = array(
'echo' => false,
'format' => '',
'description' => '',
'location' => 'primary',
'classes' => 'post-description'
);

$args = wp_parse_args( $args, $defaults );
extract( $args , EXTR_SKIP );

// Get menu
$menu_locations = get_nav_menu_locations();
$nav_items = wp_get_nav_menu_items( $menu_locations[ $location ] );

// Cycle through nav items
foreach ( $nav_items as $nav_item ) {

if ( ( is_page() || is_single() || is_archive() ) && ( $nav_item->object_id == $post->ID ) ) {
$description = $nav_item->description;
}
elseif ( ( is_category() ) && ( $nav_item->object == 'category' ) ) {
$cat = get_query_var( 'cat' );
if ( $nav_item->object_id == $cat )
$description = $nav_item->description;
}
}

// Get output formatting
if ( $format == 'html' )
$output = apply_filters( 'wps_get_menu_description_output' , '<div class="'. $classes .'">' . $description . '</div>' , $args );
else
$output = $description;

// Echo description
if ($echo)
echo $output;

// Return description
return $output;
}
[/php]

To call the function, you just set the args in an array like this:
wps_get_menu_description( array('echo' => true, 'format'=>'html', 'classes' => 'post-info') );

With most frameworks, like Genesis/Thesis, you may need to call it like this (example reflects Genesis):
[php]<?php
// Add and Customize a Tagline under the Page Title
add_action('genesis_after_post_title', 'my_tagline');
function my_tagline() {
wps_get_menu_description( array('echo' => true, 'format'=>'html', 'classes' => 'post-info') );
}[/php]

Word of Warning: Please check your descriptions, and do not assume that there is nothing there if you didn't put it there. Your theme or plugins may have inserted content there as I've seen the description contain the_content automagically.

Do you see anything that I missed? Is there something else that you wish was added?