根据菜单项的发布ID动态获取菜单项的元键值

时间:2014-02-11 作者:ghaschel

我有一个菜单,我需要插入一个图像,它的路径保存在一个元键中(_menu_item_img) 与post ID关联,每个菜单项都有自己的图像,我需要动态获取它。

我尝试的方法,在谷歌上找不到任何可以帮助我的方法。

wp_nav_menu( array( \'container\' =>false, \'theme_location\' => \'main_menu\', \'menu_id\' => \'main_menu\', \'link_before\' => get_post_meta($item->object_id, \'_menu_item_img\'))));

这是我用于将自定义条目添加到菜单页的类:

add_action( \'init\', array( \'XTeam_Nav_Menu_Item_Custom_Fields\', \'setup\' ) );

class XTeam_Nav_Menu_Item_Custom_Fields {
    static $options = array(
        \'item_tpl\' => \'
            <p class="additional-menu-field-{name} description description-thin">
                <label for="edit-menu-item-{name}-{id}">
                    {label}<br>
                    <input
                        type="{input_type}"
                        id="edit-menu-item-{name}-{id}"
                        class="widefat code edit-menu-item-{name}"
                        name="menu-item-{name}[{id}]"
                        value="{value}">
                </label>
            </p>
        \',
    );

    static function setup() {
        // @todo we can do some merging of provided options from WP options for from config
        self::$options[\'fields\'] = array(
            \'color\' => array(
                \'name\' => \'img\',
                \'label\' => __(\'Link para Imagem\', \'xteam\'),
                \'container_class\' => \'link-img\',
                \'input_type\' => \'text\',
            ),
        );

        add_filter( \'wp_edit_nav_menu_walker\', function () {
            return \'XTeam_Walker_Nav_Menu_Edit\';
        });
        add_filter( \'xteam_nav_menu_item_additional_fields\', array( __CLASS__, \'_add_fields\' ), 10, 5 );
        add_action( \'save_post\', array( __CLASS__, \'_save_post\' ) );
    }

    static function get_fields_schema() {
        $schema = array();
        foreach(self::$options[\'fields\'] as $name => $field) {
            if (empty($field[\'name\'])) {
                $field[\'name\'] = $name;
            }
            $schema[] = $field;
        }
        return $schema;
    }

    static function get_menu_item_postmeta_key($name) {
        return \'_menu_item_\' . $name;
    }

    /**
     * Inject the 
     * @hook {action} save_post
     */
    static function _add_fields($new_fields, $item_output, $item, $depth, $args) {
        $schema = self::get_fields_schema($item->ID);
        foreach($schema as $field) {
            $field[\'value\'] = get_post_meta($item->ID, self::get_menu_item_postmeta_key($field[\'name\']), true);
            $field[\'id\'] = $item->ID;
            $new_fields .= str_replace(
                array_map(function($key){ return \'{\' . $key . \'}\'; }, array_keys($field)),
                array_values(array_map(\'esc_attr\', $field)),
                self::$options[\'item_tpl\']
            );
        }
        return $new_fields;
    }

    /**
     * Save the newly submitted fields
     * @hook {action} save_post
     */
    static function _save_post($post_id) {
        if (get_post_type($post_id) !== \'nav_menu_item\') {
            return;
        }
        $fields_schema = self::get_fields_schema($post_id);
        foreach($fields_schema as $field_schema) {
            $form_field_name = \'menu-item-\' . $field_schema[\'name\'];
            if (isset($_POST[$form_field_name][$post_id])) {
                $key = self::get_menu_item_postmeta_key($field_schema[\'name\']);
                $value = stripslashes($_POST[$form_field_name][$post_id]);
                update_post_meta($post_id, $key, $value);
            }
        }
    }

}

require_once ABSPATH . \'wp-admin/includes/nav-menu.php\';
class XTeam_Walker_Nav_Menu_Edit extends Walker_Nav_Menu_Edit {
    function start_el(&$output, $item, $depth, $args) {
        $item_output = \'\';
        parent::start_el($item_output, $item, $depth, $args);
        $new_fields = apply_filters( \'xteam_nav_menu_item_additional_fields\', \'\', $item_output, $item, $depth, $args );
        // Inject $new_fields before: <div class="menu-item-actions description-wide submitbox">
        if ($new_fields) {
            $item_output = preg_replace(\'/(?=<div[^>]+class="[^"]*submitbox)/\', $new_fields, $item_output);
        }
        $output .= $item_output;
    }
}
有人能指出我在哪里漏掉了重点吗?

1 个回复
SO网友:s_ha_dum

此代码:

wp_nav_menu( array( \'container\' =>false, \'theme_location\' => \'main_menu\', \'menu_id\' => \'main_menu\', \'link_before\' => get_post_meta($item->object_id, \'_menu_item_img\'))));
让我认为,当您尝试显示值时,前端出现了问题。可读性(无需额外的)):

wp_nav_menu( 
  array( 
    \'container\' =>false, 
    \'theme_location\' => \'main_menu\', 
    \'menu_id\' => \'main_menu\', 
    \'link_before\' => get_post_meta($item->object_id, \'_menu_item_img\')
  )
);
本质上,问题是纯PHP。如果你有debugging enabled 你会注意到Notice 在代码运行的行上。那是因为$item 此时未定义。$item 定义为walker回调实际执行,但PHP不会注意到您的变量,并等待稍后尝试理解它。当它被使用时,它就在那里被处理。

您需要为前端显示创建一个自定义漫游器(something like this).

过滤器打开the_title 也可以这样做:

function pre_title_wpse_134186($title) {
  return \'test\'.$title;
}
add_filter(\'the_title\',\'pre_title_wpse_134186\');
wp_nav_menu( 
  array( 
    \'container\' =>false, 
    \'theme_location\' => \'main_menu\', 
    \'menu_id\' => \'main_menu\',
  )
);
remove_filter(\'the_title\',\'pre_title_wpse_134186\');

结束

相关推荐

How to add taxonomy in menus?

书籍(自定义帖子类型)小说(税)科学(税)历史(税)--书籍体裁(税务)小说(术语)科学(学期)历史(学期)以下哪一项是做这件事的“好方法”?对于前一个(这是我目前在管理菜单中的功能,我为每个功能都提供了“register\\u taxonomy”功能),我无法选择要在菜单中显示的“Tax”。而对于后者,我可以将它们添加到菜单中,只需要一个“register\\u taxonomy”函数。