Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WordPress allow HTML in menu description

I looked all over how to allow HTML with links or other tags inside the menu description, but all I can find is how to strip tags with

// Allow HTML descriptions in WordPress Menu
remove_filter( 'nav_menu_description', 'strip_tags' );

I found this function, that should allow writing links, and other HTML elements in menu description

add_filter( 'wp_setup_nav_menu_item', 'cus_wp_setup_nav_menu_item' );
function cus_wp_setup_nav_menu_item( $menu_item ) {
     $menu_item->description = (isset($menu_item->post_content)) ? apply_filters( 'nav_menu_description', $menu_item->post_content ) : '';
     return $menu_item;
}

But this will output the page contents in the menu description :\

Any other way around this?

like image 571
dingo_d Avatar asked May 31 '26 01:05

dingo_d


1 Answers

I think your code should look like this:

remove_filter( 'nav_menu_description', 'strip_tags' );

function my_plugin_wp_setup_nav_menu_item( $menu_item ) {
    if ( isset( $menu_item->post_type ) ) {
        if ( 'nav_menu_item' == $menu_item->post_type ) {
            $menu_item->description = apply_filters( 'nav_menu_description', $menu_item->post_content );
        }
    }

    return $menu_item;
}

add_filter( 'wp_setup_nav_menu_item', 'my_plugin_wp_setup_nav_menu_item' );

How does your walker class look like? You may not need the my_plugin_wp_setup_nav_menu_item filter if you use the value of $item->post_content insted of $item->description. Also make sure to print the raw value of the menu item description without escaping it with esc_html or esc_attr.

like image 65
cdog Avatar answered Jun 01 '26 21:06

cdog



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!