Skip to content

Instantly share code, notes, and snippets.

@anttiviljami
Last active January 5, 2024 14:25
Show Gist options
  • Star 30 You must be signed in to star a gist
  • Fork 14 You must be signed in to fork a gist
  • Save anttiviljami/3cdefd6b5556d80426e66f131a42bef1 to your computer and use it in GitHub Desktop.
Save anttiviljami/3cdefd6b5556d80426e66f131a42bef1 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>
@MikeiLL
Copy link

MikeiLL commented Aug 2, 2017

Thanks for this, man. The links above were helpful.

@eversionsystems
Copy link

eversionsystems commented Dec 13, 2018

If you need to enqueue jquery-ui, make sure you use the correct id which is 'jquery-ui-core'

wp_enqueue_script('jquery-ui-core');

@lordspace
Copy link

you were missing

<a href="#" class="open-my-dialog">open</a>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment