Skip to content

Instantly share code, notes, and snippets.

@lkoudal
Forked from anttiviljami/wp-admin-modal-dialog.php
Created December 13, 2021 20:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lkoudal/308404a4c850d115d32402fb1de5ff1d to your computer and use it in GitHub Desktop.
Save lkoudal/308404a4c850d115d32402fb1de5ff1d to your computer and use it in GitHub Desktop.
WordPress admin modal dialog example
<?php
// enqueue these scripts and styles before admin_head
wp_enqueue_script( 'jquery-ui-dialog' ); // jquery and jquery-ui should be dependencies, didn't check though...
wp_enqueue_style( 'wp-jquery-ui-dialog' );
?>
<!-- The modal / dialog box, hidden somewhere near the footer -->
<div id="my-dialog" class="hidden" style="max-width:800px">
<h3>Dialog content</h3>
<p>This is some terribly exciting content inside this dialog. Don't you agree?</p>
<p>I'm just adding some more content to make this look more like actual content.</p>
<p><strong>Look!</strong> There's a horse with a moustache behind this modal!</p>
<p>...</p>
<p>...</p>
<p>You <em>idiot</em>, horses can't have facial hair.</p>
<p>I bet you feel real stupid right now.</p>
</div>
<!-- This script should be enqueued properly in the footer -->
<script>
(function ($) {
// initalise the dialog
$('#my-dialog').dialog({
title: 'My Dialog',
dialogClass: 'wp-dialog',
autoOpen: false,
draggable: false,
width: 'auto',
modal: true,
resizable: false,
closeOnEscape: true,
position: {
my: "center",
at: "center",
of: window
},
open: function () {
// close dialog by clicking the overlay behind it
$('.ui-widget-overlay').bind('click', function(){
$('#my-dialog').dialog('close');
})
},
create: function () {
// style fix for WordPress admin
$('.ui-dialog-titlebar-close').addClass('ui-button');
},
});
// bind a button or a link to open the dialog
$('a.open-my-dialog').click(function(e) {
e.preventDefault();
$('#my-dialog').dialog('open');
});
})(jQuery);
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment