I create a WP theme and write a settings page for it. I want the user to be able to change the site logo by clicking on the button that opens the beautiful WordPress "Insert media file" window. I found some excerpts of instructions on the Internet and now I have this code (see below).
As a result, admin.js works correctly, but when I click on the "insert record" in the dialog box, I get the document.getElementById(...) is null error in the console file load-scripts.php . I think I might have confused something with the order of connecting files or missed some kind of dependency. I'm new to WordPress :) I hope for some tips on how to fix it or how to implement it correctly.
functions.php
function true_include_myuploadscript() { if (!did_action('wp_enqueue_media')) { wp_enqueue_media(); } wp_enqueue_script('myuploadscript', get_template_directory_uri().'/js/admin.js', ['jquery'], null, false); } function true_image_uploader_field($name, $value = '', $w = 757, $h = 265) { $default = get_template_directory_uri() . '/img/fenix_logo.png'; if ($value) { $image_attributes = wp_get_attachment_image_src($value, [$w, $h]); $src = $image_attributes[0]; } else { $src = $default; }?> <div> <img class="upload-image" data-src="<?php echo $default; ?>" src="<?php echo $src; ?>" width="<?php echo $w; ?>px" height="<?php echo $h; ?>px"> <input type="hidden" name="<?php echo $name; ?>" id="<?php echo $name; ?>" value="<?php echo $value; ?>"> <button class="upload-image upload-image-btn">Загрузить</button> <button class="remove-image-btn">×</button> </div> <?php } ... I skip the HTML markup of the settings page itself. In it, just in the middle, the function is called as follows:
<?php if (function_exists('true_image_uploader_field')) { true_image_uploader_field('phoenix_logo', get_option('phoenix_logo')); } ?> ...
function setup_theme_admin_menu() { add_submenu_page( 'themes.php', 'Настройки внешнего вида темы', 'Настройки темы', 'manage_options', 'theme_settings', 'theme_options' ); } add_action('admin_menu', 'setup_theme_admin_menu'); add_action('admin_enqueue_scripts', 'true_include_myuploadscript'); At the very top, the admin.js file is admin.js — this is its contents:
jQuery(function($) { $('.upload-image').click(function() { var send_attachment_bkp = wp.media.editor.send.attachment; var parent = $(this).parent(); wp.media.editor.send.attachment = function(props, attachment) { parent.children('.upload-image').attr('src', attachment.url); parent.children('input').val(attachment.id); wp.media.editor.send.attachment = send_attachment_bkp; }; wp.media.editor.open(parent.children('.upload-image-button')); return false; }); $('.remove-image-btn').click(function() { var parent = $(this).parent(); if (confirm("Вы действительно хотите удалить это изображение?")) { var image = parent.children('.upload-image'); image.attr('src', image.data('src')); parent.children('input').val(''); } return false; }); });