如何解决用于在没有插件的情况下在 WordPress 的菜单中上传图像的挂钩事件
我必须在下拉菜单中添加图片。我知道我可以用 CSS Classes (optional)
做到这一点,但我不想这样做。我想动态添加,而不是打开代码修改或添加。
我正在做的是,我有我的产品,我必须将我的产品连同产品图片和标题一起添加到下拉菜单中。
我的期望下拉输出
我不想使用任何插件。我需要一个自定义代码来解决这个问题。我正在使用下面的代码。你会帮我解决这个问题吗?
//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 举报,一经查实,本站将立刻删除。