在使用wordpress做独立站的过程中,如何给上传的每张图片自动地添加alt文本,可以看下面地代码,将下面的代码添加到网站的functions.php文件中或者使用code snippet等插件。最好使用code snippet插件,这样以后主题升级,不会导致网站的代码被覆盖。
function enqueue_custom_inline_admin_script() { ?> <script type="text/javascript"> jQuery(document).ready(function($) { function updateAltText() { var imageTitle1 = $("#attachment-details-title").val(); var imageTitle2 = $("#attachment-details-two-column-title").val(); if (typeof imageTitle1 === 'string') { imageTitle1 = imageTitle1.replace(/-/g, ' '); $("#attachment-details-title").val(imageTitle1); } else { imageTitle1 = ""; } if (typeof imageTitle2 === 'string') { imageTitle2 = imageTitle2.replace(/-/g, ' '); $("#attachment-details-two-column-title").val(imageTitle2); } else { imageTitle2 = ""; } var altTextField1 = $("#attachment-details-alt-text"); var altTextField2 = $("#attachment-details-two-column-alt-text"); if (altTextField1.length && (altTextField1.val().trim() === "" || altTextField1.val().trim() === imageTitle1)) { altTextField1.val(imageTitle1); } if (altTextField2.length && (altTextField2.val().trim() === "" || altTextField2.val().trim() === imageTitle2)) { altTextField2.val(imageTitle2); } } $(document).on("click", ".media-modal-close, .media-button-select, .attachment, .attachment-preview", function() { setTimeout(updateAltText, 500); }); $(document).on("DOMNodeInserted", function(e) { if ($(e.target).find("#attachment-details-alt-text, #attachment-details-two-column-alt-text").length) { setTimeout(updateAltText, 500); } }); }); </script> <?php } add_action('admin_head', 'enqueue_custom_inline_admin_script');