如何基于自定义高级菜单选项向Wordpress导航菜单项添加类

如何解决如何基于自定义高级菜单选项向Wordpress导航菜单项添加类

我发现此代码使我可以将自定义字段添加到Wordpress菜单编辑器中的高级选项:

/*
 * Saves new field to postmeta for navigation
 */
add_action('wp_update_nav_menu_item','megamenu_nav_update',10,3);
function megamenu_nav_update($menu_id,$menu_item_db_id,$args ) {
    if ( is_array($_REQUEST['menu-item-megamenu']) ) {
        $megamenu_value = $_REQUEST['menu-item-megamenu'][$menu_item_db_id];
        update_post_meta( $menu_item_db_id,'_menu_item_megamenu',$megamenu_value );
    }
    if ( is_array($_REQUEST['menu-item-megamenu_col']) ) {
        $megamenu_col_value = $_REQUEST['menu-item-megamenu_col'][$menu_item_db_id];
        update_post_meta( $menu_item_db_id,'_menu_item_megamenu_col',$megamenu_col_value );
    }
    if ( is_array($_REQUEST['menu-item-megamenu_alignment']) ) {
        $megamenu_alignment_value = $_REQUEST['menu-item-megamenu_alignment'][$menu_item_db_id];
        update_post_meta( $menu_item_db_id,'_menu_item_megamenu_alignment',$megamenu_alignment_value );
    }
}

/*
 * Adds value of new field to $item object that will be passed to     Walker_Nav_Menu_Edit_Custom
 */
add_filter( 'wp_setup_nav_menu_item','megamenu_nav_item' );
function megamenu_nav_item($menu_item) {
    $menu_item->megamenu = get_post_meta( $menu_item->ID,true );
    $menu_item->megamenu_col = get_post_meta( $menu_item->ID,true );
    $menu_item->megamenu_alignment = get_post_meta( $menu_item->ID,true );
    return $menu_item;
}

add_filter( 'wp_edit_nav_menu_walker','custom_nav_edit_walker',2 );
function custom_nav_edit_walker($walker,$menu_id) {
    return 'Walker_Nav_Menu_Edit_Custom';
}

/**
 * Copied from Walker_Nav_Menu_Edit class in core
 * 
 * Create HTML list of nav menu input items.
 *
 * @package WordPress
 * @since 3.0.0
 * @uses Walker_Nav_Menu
 */

class Walker_Nav_Menu_Edit_Custom extends Walker_Nav_Menu  {
    /**
     * @see Walker_Nav_Menu::start_lvl()
     * @since 3.0.0
     *
     * @param string $output Passed by reference.
     */
     
    
     
    function start_lvl(&$output,$depth = 0,$args = array()) { 
    }
    
    /**
     * @see Walker_Nav_Menu::end_lvl()
     * @since 3.0.0
     *
     * @param string $output Passed by reference.
     */
    function end_lvl(&$output,$args = array()) {
    }
    
    /**
     * @see Walker::start_el()
     * @since 3.0.0
     *
     * @param string $output Passed by reference. Used to append additional content.
     * @param object $item Menu item data object.
     * @param int $depth Depth of menu item. Used for padding.
     * @param object $args
     */
    function start_el(&$output,$item,$args = array(),$id = 0) {
        global $_wp_nav_menu_max_depth;
       
        $_wp_nav_menu_max_depth = $depth > $_wp_nav_menu_max_depth ? $depth : $_wp_nav_menu_max_depth;
    
        $indent = ( $depth ) ? str_repeat( "\t",$depth ) : '';
    
        ob_start();
        $item_id = esc_attr( $item->ID );
        $removed_args = array(
            'action','customlink-tab','edit-menu-item','menu-item','page-tab','_wpnonce',);
    
        $original_title = '';
        if ( 'taxonomy' == $item->type ) {
            $original_title = get_term_field( 'name',$item->object_id,$item->object,'raw' );
            if ( is_wp_error( $original_title ) )
                $original_title = false;
        } elseif ( 'post_type' == $item->type ) {
            $original_object = get_post( $item->object_id );
            $original_title = $original_object->post_title;
        }
    
        $classes = array(
            'menu-item menu-item-depth-' . $depth,'menu-item-' . esc_attr( $item->object ),'menu-item-edit-' . ( ( isset( $_GET['edit-menu-item'] ) && $item_id == $_GET['edit-menu-item'] ) ? 'active' : 'inactive'),);
    
        $title = $item->title;
    
        if ( ! empty( $item->_invalid ) ) {
            $classes[] = 'menu-item-invalid';
            /* translators: %s: title of menu item which is invalid */
            $title = sprintf( __( '%s (Invalid)','rdesign' ),$item->title );
        } elseif ( isset( $item->post_status ) && 'draft' == $item->post_status ) {
            $classes[] = 'pending';
            /* translators: %s: title of menu item in draft status */
            $title = sprintf( __('%s (Pending)','rdesign'),$item->title );
        }
    
        $title = empty( $item->label ) ? $title : $item->label;
    
        ?>
        <li id="menu-item-<?php echo esc_attr($item_id); ?>" class="<?php echo implode(' ',$classes ); ?>">
            <dl class="menu-item-bar">
                <dt class="menu-item-handle">
                    <span class="item-title"><?php echo esc_html( $title ); ?></span>
                    <span class="item-controls">
                        <span class="item-type"><?php echo esc_html( $item->type_label ); ?></span>
                        <span class="item-order hide-if-js">
                            <a href="<?php
                                echo wp_nonce_url( esc_url( add_query_arg(
                                        array(
                                            'action' => 'move-up-menu-item','menu-item' => $item_id,),remove_query_arg($removed_args,admin_url( 'nav-menus.php' )))
                                    ),'move-menu_item'
                                );
                            ?>" class="item-move-up"><abbr title="<?php esc_attr_e('Move up','rdesign'); ?>">&#8593;</abbr></a>
                            |
                            <a href="<?php
                                echo wp_nonce_url(
                                esc_url( add_query_arg(
                                        array(
                                            'action' => 'move-down-menu-item',admin_url( 'nav-menus.php' ) ) )
                                    ),'move-menu_item'
                                );
                            ?>" class="item-move-down"><abbr title="<?php esc_attr_e('Move down','rdesign'); ?>">&#8595;</abbr></a>
                        </span>
                        <a class="item-edit" id="edit-<?php echo esc_attr($item_id); ?>" title="<?php esc_attr_e('Edit Menu Item','rdesign'); ?>" href="<?php
                            echo ( isset( $_GET['edit-menu-item'] ) && $item_id == $_GET['edit-menu-item'] ) ? admin_url( 'nav-menus.php' ) : esc_url( add_query_arg( 'edit-menu-item',$item_id,remove_query_arg( $removed_args,admin_url( 'nav-menus.php#menu-item-settings-' . $item_id ) ) ) );
                        ?>"><?php _e( 'Edit Menu Item','rdesign' ); ?></a>
                    </span>
                </dt>
            </dl>
    
            <div class="menu-item-settings" id="menu-item-settings-<?php echo esc_attr($item_id); ?>">
                <?php if( 'custom' == $item->type ) : ?>
                    <p class="field-url description description-wide">
                        <label for="edit-menu-item-url-<?php echo esc_attr($item_id); ?>">
                            <?php _e( 'URL','rdesign' ); ?><br />
                            <input type="text" id="edit-menu-item-url-<?php echo esc_attr($item_id); ?>" class="widefat code edit-menu-item-url" name="menu-item-url[<?php echo esc_attr($item_id); ?>]" value="<?php echo esc_attr( $item->url ); ?>" />
                        </label>
                    </p>
                <?php endif; ?>
                <p class="description description-thin">
                    <label for="edit-menu-item-title-<?php echo esc_attr($item_id); ?>">
                        <?php _e( 'Navigation Label','rdesign' ); ?><br />
                        <input type="text" id="edit-menu-item-title-<?php echo esc_attr($item_id); ?>" class="widefat edit-menu-item-title" name="menu-item-title[<?php echo esc_attr($item_id); ?>]" value="<?php echo esc_attr( $item->title ); ?>" />
                    </label>
                </p>
                <p class="description description-thin">
                    <label for="edit-menu-item-attr-title-<?php echo esc_attr($item_id); ?>">
                        <?php _e( 'Title Attribute','rdesign' ); ?><br />
                        <input type="text" id="edit-menu-item-attr-title-<?php echo esc_attr($item_id); ?>" class="widefat edit-menu-item-attr-title" name="menu-item-attr-title[<?php echo esc_attr($item_id); ?>]" value="<?php echo esc_attr( $item->post_excerpt ); ?>" />
                    </label>
                </p>
                <p class="field-link-target description">
                    <label for="edit-menu-item-target-<?php echo esc_attr($item_id); ?>">
                        <input type="checkbox" id="edit-menu-item-target-<?php echo esc_attr($item_id); ?>" value="_blank" name="menu-item-target[<?php echo esc_attr($item_id); ?>]"<?php checked( $item->target,'_blank' ); ?> />
                        <?php _e( 'Open link in a new window/tab','rdesign' ); ?>
                    </label>
                </p>
                <p class="field-css-classes description description-thin">
                    <label for="edit-menu-item-classes-<?php echo esc_attr($item_id); ?>">
                        <?php _e( 'CSS Classes (optional)','rdesign' ); ?><br />
                        <input type="text" id="edit-menu-item-classes-<?php echo esc_attr($item_id); ?>" class="widefat code edit-menu-item-classes" name="menu-item-classes[<?php echo esc_attr($item_id); ?>]" value="<?php echo esc_attr( implode(' ',$item->classes ) ); ?>" />
                    </label>
                </p>
                <p class="field-xfn description description-thin">
                    <label for="edit-menu-item-xfn-<?php echo esc_attr($item_id); ?>">
                        <?php _e( 'Link Relationship (XFN)','rdesign' ); ?><br />
                        <input type="text" id="edit-menu-item-xfn-<?php echo esc_attr($item_id); ?>" class="widefat code edit-menu-item-xfn" name="menu-item-xfn[<?php echo esc_attr($item_id); ?>]" value="<?php echo esc_attr( $item->xfn ); ?>" />
                    </label>
                </p>
                <?php
                /* New fields insertion starts here */
                ?>      
                <p class="field-megamenu-status description description-wide">
                    <label for="edit-menu-item-megamenu-<?php echo esc_attr($item_id); ?>">
                    <input type="checkbox" id="edit-menu-item-megamenu-<?php echo esc_attr($item_id); ?>" value="megamenu" name="menu-item-megamenu[<?php echo esc_attr($item_id); ?>]"<?php checked( $item->megamenu,'megamenu' ); ?> />
                    <?php _e( 'Enable megamenu','rdesign' );    ?>
                    </label>
                </p>

                <p class="field-megamenu-columns description description-wide">
                    <label for="edit-menu-item-megamenu_col-<?php echo esc_attr($item_id); ?>">
                        <?php _e( 'Megamenu columns (from 2 to 6)','rdesign' ); ?><br />
                        <?php $saved_megamenu_col = esc_attr( $item->megamenu_col ); ?>
                        <select id="edit-menu-item-megamenu_col-<?php echo esc_attr($item_id); ?>" class="widefat code edit-menu-item-custom" name="menu-item-megamenu_col[<?php echo esc_attr($item_id); ?>]">
                            <option value="2" <?php if($saved_megamenu_col == "2"){echo("selected");} ?>>2</option>
                            <option value="3" <?php if($saved_megamenu_col == "3"){echo("selected");} ?>>3</option>
                            <option value="4" <?php if($saved_megamenu_col == "4"){echo("selected");} ?>>4</option>
                            <option value="5" <?php if($saved_megamenu_col == "5"){echo("selected");} ?>>5</option>
                            <option value="6" <?php if($saved_megamenu_col == "6"){echo("selected");} ?>>6</option>
                        </select>
                </label>
                </p>

                <p class="field-megamenu-alignment description description-wide">
                    <label for="edit-menu-item-megamenu_alignment-<?php echo esc_attr($item_id); ?>">
                        <?php _e( 'Megamenu alignment','rdesign' ); ?><br />
                        <?php $saved_megamenu_alignment = esc_attr( $item->megamenu_alignment ); ?>
                        <select id="edit-menu-item-megamenu_alignment-<?php echo esc_attr($item_id); ?>" class="widefat code edit-menu-item-custom" name="menu-item-megamenu_alignment[<?php echo esc_attr($item_id); ?>]">
                            <option value="left" <?php if($saved_megamenu_alignment == "left"){echo("selected");} ?>>Left</option>
                            <option value="center" <?php if($saved_megamenu_alignment == "center"){echo("selected");} ?>>Center</option>
                            <option value="right" <?php if($saved_megamenu_alignment == "right"){echo("selected");} ?>>Right</option>
                            <option value="space-around" <?php if($saved_megamenu_alignment == "space-around"){echo("selected");} ?>>Space Around</option>
                            <option value="space-evenly" <?php if($saved_megamenu_alignment == "space-evenly"){echo("selected");} ?>>Space Evenly</option>
                            <option value="space-between" <?php if($saved_megamenu_alignment == "space-between"){echo("selected");} ?>>Space Between</option>
                        </select>
                    </label>
                </p>
                <?php
                /* New fields insertion ends here */
                ?>
                <div class="menu-item-actions description-wide submitbox">
                    <?php if( 'custom' != $item->type && $original_title !== false ) : ?>
                        <p class="link-to-original">
                            <?php printf( __('Original: %s','<a href="' . esc_attr( $item->url ) . '">' . esc_html( $original_title ) . '</a>' ); ?>
                        </p>
                    <?php endif; ?>
                    <a class="item-delete submitdelete deletion" id="delete-<?php echo esc_attr($item_id); ?>" href="<?php
                    echo wp_nonce_url(
                    esc_url( add_query_arg(
                            array(
                                'action' => 'delete-menu-item',admin_url( 'nav-menus.php' ) ) )
                        ),'delete-menu_item_' . $item_id
                    ); ?>"><?php _e('Remove','rdesign'); ?></a> <span class="meta-sep"> | </span> <a class="item-cancel submitcancel" id="cancel-<?php echo esc_attr($item_id); ?>" href="<?php echo esc_url( add_query_arg( array('edit-menu-item' => $item_id,'cancel' => time()),admin_url( 'nav-menus.php' ) ) ) );
                        ?>#menu-item-settings-<?php echo esc_attr($item_id); ?>"><?php _e('Cancel','rdesign'); ?></a>
                </div>
    
                <input class="menu-item-data-db-id" type="hidden" name="menu-item-db-id[<?php echo esc_attr($item_id); ?>]" value="<?php echo esc_attr($item_id); ?>" />
                <input class="menu-item-data-object-id" type="hidden" name="menu-item-object-id[<?php echo esc_attr($item_id); ?>]" value="<?php echo esc_attr( $item->object_id ); ?>" />
                <input class="menu-item-data-object" type="hidden" name="menu-item-object[<?php echo esc_attr($item_id); ?>]" value="<?php echo esc_attr( $item->object ); ?>" />
                <input class="menu-item-data-parent-id" type="hidden" name="menu-item-parent-id[<?php echo esc_attr($item_id); ?>]" value="<?php echo esc_attr( $item->menu_item_parent ); ?>" />
                <input class="menu-item-data-position" type="hidden" name="menu-item-position[<?php echo esc_attr($item_id); ?>]" value="<?php echo esc_attr( $item->menu_order ); ?>" />
                <input class="menu-item-data-type" type="hidden" name="menu-item-type[<?php echo esc_attr($item_id); ?>]" value="<?php echo esc_attr( $item->type ); ?>" />
            </div><!-- .menu-item-settings-->
            <ul class="menu-item-transport"></ul>
        <?php
        
        $output .= ob_get_clean();

        }
}

此代码使我可以添加一个复选框字段以启用Megamenu,一个下拉字段为Megamenu选择2-6列,并为一个下拉字段选择megamenu物品对齐方式。

但是,我现在需要知道的是保存了这些选项,现在如何根据保存的值将类添加到导航菜单项中?即,如果启用了Megamenu,则需要将“ mega-menu”类添加到菜单项

  • 解决方法

    好,我设法使用以下代码使它正常工作:

    add_filter('nav_menu_css_class','megamenu_nav_classes',10,2);
    function megamenu_nav_classes($classes,$item){
        $item_id = esc_attr( $item->ID );
        $mega_menu = $item->$megamenu['_menu_item_megamenu'][0];
        $mega_menu_col = $item->$megamenu['_menu_item_megamenu_col'][0];
        $mega_menu_alignment = $item->$megamenu['_menu_item_megamenu_alignment'][0];
    
         if($mega_menu == 'megamenu'){
            $classes[] = 'mega-menu';
            $classes[] = 'col-'.$mega_menu_col;
            $classes[] = $mega_menu_alignment;
         }
    
         return $classes;
    }
    

    这确实有效,但是谁能告诉我这是否是解决此问题的最佳方法?还是有更好的“清洁”方法?

    版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

    相关推荐


    依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
    错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
    错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
    错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
    报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
    解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
    删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
    查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
    使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
    错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
    错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
    错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
    报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
    错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
    错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
    错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
    参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
    使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-