用于在没有插件的情况下在 WordPress 的菜单中上传图像的挂钩事件

问题描述

我必须在下拉菜单添加图片。我知道我可以用 CSS Classes (optional) 做到这一点,但我不想这样做。我想动态添加,而不是打开代码修改添加

我正在做的是,我有我的产品,我必须将我的产品连同产品图片标题一起添加到下拉菜单中。

我的期望下拉输出

enter image description here

我不想使用任何插件。我需要一个自定义代码解决这个问题。我正在使用下面的代码。你会帮我解决这个问题吗?

//hook event for upload image on menu
function add_image_on_menu_module()
{
    // Add these actions for  add
    add_action('create_menu','save_image');
    add_action('menu_add_form_fields','add_image_menu');//display image upload option on menu
}
add_action('init','add_image_on_menu_module');

//display image upload option 
function add_image_menu($tag)
{
    $menu_image = get_option('menu_image');
    $menu_img = '';
    if (is_array($menu_image) && array_key_exists($tag->term_id,$menu_image)) {
        $menu_img = $menu_image[$tag->term_id];
    }
    ?>
    <div>
        <p><label>Image</label></p>
        <p>
            <?PHP
                if ($menu_img != "") {
                    ?>
                <img src="<?PHP echo $menu_img; ?>" alt="" title=""  style="width:300px;"  />
            <?PHP
                }
                ?>
            <br />
            <!-- Add this html here -->
            <input type="text" class="regular-text" id="custom_menu_image" name="menu_image" value="<?PHP echo $menu_img; ?>">
            <button class="set_menu_image button">Set Image url</button>
        </p>
    </div>

<?PHP
}


function save_image($term_id)
{
    if (isset($_POST['menu_image'])) {
        //load existing category featured option
        $menu_image = get_option('menu_image');
        //set featured post ID to proper category ID in options array
        $menu_image[$term_id] =  $_POST['menu_image'];
        //save the option array
        update_option('menu_image',$menu_image);
    }
}


// Enquey media elements
add_action('admin_enqueue_scripts',function () {
    if (is_admin())
        wp_enqueue_media();
});

// Add JS using admin_footer or enque thorugh hooks
add_action('admin_footer','my_footer_scripts');
function my_footer_scripts()
{
    ?>
    <script>
        jQuery(document).ready(function() {
            if (jQuery('.set_menu_image').length > 0) {
                if (typeof wp !== 'undefined' && wp.media && wp.media.editor) {
                    jQuery('.set_menu_image').on('click',function(e) {
                        e.preventDefault();
                        var button = jQuery(this);
                        var url_input = jQuery("#custom_menu_image");
                        wp.media.editor.send.attachment = function(props,attachment) {
                            url_input.val(attachment.url);
                        };
                        wp.media.editor.open(button);
                        return false;
                    });
                }
            }
        });
    </script>
<?PHP
}
 ?>

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)