Adding Modal Windows in the WordPress Admin Without JavaScript
When creating a theme or plugin for WordPress which requires users to read some documentation, it is a good idea to display the documentation right within the WordPress admin. Otherwise, making the user browse an external site could produce a negative experience from the additional friction.
I have written about displaying documentation within Gutenberg, which enables to make use of the available React-based components for different use cases. For instance, we can display our documentation by reusing the <Guide> component:
However, what happens if we are not operating within Gutenberg? For instance, we may have coded our plugin long time ago, and migrating it to Gutenberg is too much of an effort. In that case, how could we manage to open a modal window in the WordPress admin?
Unsurprisingly, we can reuse any functionality shipped anywhere by WordPress, not just through Gutenberg. And WordPress does already provide an implementation of a modal window, which is originally used to display plugin information:
Even though designed for plugins, the modal window can nevertheless display any arbitrary content, since it is simply an iframe embedding the intended page, for any page from the same domain. And opening the modal window can be triggered from anywhere within the WordPress admin, not just from within the plugins page.
For instance, similar to the plugins page, our plugin could print a table with custom entries, and a “View details” link below each entry:
And when clicking on this link, it opens a modal window to display the entry’s corresponding documentation:
In this article we will learn how to do this. The goal is to reuse the WordPress admin’s modal windows for our own themes or plugins, without depending on Gutenberg for this basic functionality.
Loading the JS/CSS assets
WordPress handles the modal windows through the following 3 files:
File wp-includes/js/thickbox/thickbox.js loads ThickBox, the library that provides the functionality for the modal window.
File wp-includes/js/thickbox/thickbox.css gives the styles for the modal window, including its placement on the page, and transitions when opening/closing the modal.
File wp-admin/js/plugin-install.js loads the event which, when clicking on a corresponding link, opens the modal window.
WordPress loads these 3 files for the plugins page:
However, these files are not always loaded in the WordPress admin, only in the plugins page. So, we must add some code to load them in the page where we want to open the modal window. Since the 3 assets are already registered (through file wp-includes/script-loader.php), we can simply enqueue them for the corresponding page:
add_action('admin_enqueue_scripts', 'enqueue_modal_window_assets');
function enqueue_modal_window_assets()
{
// Check that we are on the right screen
if (get_current_screen()->id == 'my_menu_page') {
// Enqueue the assets
wp_enqueue_style('thickbox');
wp_enqueue_script('plugin-install');
}
}
This code loads the assets for a menu page with slug "my_menu_page". Enqueuing file plugin-install.js also loads thickbox.js, so we can skip enqueueing this latter one.
Printing the link to open the modal window
The JavaScript assets introduced above load the modal window in the page, and listen for certain links to be clicked; when that happens, the URL under the link’s href attribute is extracted, and loaded into the modal window’s iframe.
The following code will print a link which, upon clicking, will open the modal window and load within a custom page from the WordPress admin:
Mandatory classnames "thickbox" and "open-plugin-details-modal"; without these, when clicked the link would be treated normally, opening the URL in the browser window
URL parameter TB_iframe=true; otherwise, the modal window opens with an unsuitable format
URL parameters width and height are added by the ThickBox library when calculating the iframe dimensions based on the viewport’s size; the WordPress code contains these parameters in advance on the links (for instance, here) but manually adding them or not makes no difference
Optional attribute data-title allows to set the iframe‘s title attribute; otherwise, "Plugin details" is used
When clicking the link, the JavaScript logic creates a new iframe with the URL under the link’s href attribute, minus its parameters TB_iframe, width and height. Then, to let our page know that it is being opened inside the modal window, we further add URL parameter modal_window=true.
Printing the menu page or the modal window
In the WordPress admin, we add pages for our plugin through functions add_menu_page and add_submenu_page. Registered under its own slug, each page is accessed under admin.php?page=menu_page_slug.
In order to display content in the modal window, this has to be registered as a menu page; but then, this page would also be accessible through the admin menu on its own:
This is something we want to avoid: a link to open the modal window’s contents on its own must not be added to the menu.
We use URL parameter modal_window added to the link above to provide a solution to this problem: we always register a single page under my_menu_page, and then print either the content for the normal page, or the content for the modal window, depending on parameter modal_window being present on the URL or not:
add_action('admin_menu', 'register_my_custom_menu_page');
function register_my_custom_menu_page() {
// If requesting the modal window, print a different output
$option_function = $_REQUEST['modal_window'] ? 'print_modal_window' : 'print_menu_page';
add_menu_page(
__('My Menu Page'),
'my menu',
'manage_options',
'my_menu_page',
$output_function
);
}
/**
* Print the contents for the normal menu page
*/
function print_menu_page() {
// ...
}
/**
* Print the contents displayed within the modal window
*/
function print_modal_window() {
// ...
}
Hiding the admin menu inside the modal window
Because the modal window is being registered as a menu page, it will display the top admin bar:
To hide the admin bar, we create an extra modal-window.css file for the modal window:
And we load this file whenever the parameter modal_window is present in the URL:
add_action('admin_enqueue_scripts', 'enqueue_modal_window_css');
function enqueue_modal_window_css()
{
// Check that we are on the right screen
if (get_current_screen()->id == 'my_menu_page' && $_REQUEST['modal_window']) {
wp_enqueue_style('modal-window', plugins_url('css/modal-window.css', __FILE__));
}
}
Adjusting the styles inside the modal window
Finally, when printing the contents of the modal window, they may not be directly suitable for this format. For instance, images are by default not resized to fit within the viewport:
To fix this style (and any other that might arise from some particular content), we first wrap the content with a div with classname "modal-window-container":
function print_modal_window()
{
print('<div class="modal-window-container">');
// ...
print('</div>');
}
And now, we can add the necessary styles in file modal-window.css (added above). To make the images fit within the viewport, we add this CSS code:
Now, images display properly within the modal window:
End result and conclusion
Putting all pieces together, we can appreciate the end result:
Opening modal windows in the WordPress admin can be useful for our themes and plugins, for displaying information to our users. Since this functionality is already shipped within WordPress, it can be achieved very easily, with just a few lines of PHP and CSS code.
Related Posts
About Leonardo Losoviz
Leonardo Losoviz is an open source developer and technical writer, author of GraphQL by PoP, a CMS-agnostic GraphQL server in PHP. Find him on his blog leoloso.com and on Twitter @losoviz.
Reader Interactions
Droppin' design bombs every week! 5,751 subscriber so far!
That again was no use: he but got another smile and a friendly look of the sort he no longer wanted. I said I thought I could gallop if Harry could, and in a few minutes we were up with the ambulance. It had stopped. There were several men about it, including Sergeant Jim and Kendall, which two had come from Quinn, and having just been in the ambulance, at Ferry's side, were now remounting, both of them openly in tears. "Hello, Kendall." We have this great advantage in dealing with Plato—that his philosophical writings have come down to us entire, while the thinkers who preceded him are known only through fragments and second-hand reports. Nor is the difference merely accidental. Plato was the creator of speculative literature, properly so called: he was the first and also the greatest artist that ever clothed abstract thought in language of appropriate majesty and splendour; and it is probably to their beauty of form that we owe the preservation of his writings. Rather unfortunately, however, along with the genuine works of the master, a certain number of pieces have been handed down to us under his name, of which some are almost universally admitted to be spurious, while the authenticity of others is a question on which the best scholars are still divided. In the absence of any very cogent external evidence, an immense amount of industry and learning has been expended on this subject, and the arguments employed on both sides sometimes make us doubt whether the reasoning powers of philologists are better developed than, according to Plato, were those of mathematicians in his time. The176 two extreme positions are occupied by Grote, who accepts the whole Alexandrian canon, and Krohn, who admits nothing but the Republic;115 while much more serious critics, such as Schaarschmidt, reject along with a mass of worthless compositions several Dialogues almost equal in interest and importance to those whose authenticity has never been doubted. The great historian of Greece seems to have been rather undiscriminating both in his scepticism and in his belief; and the exclusive importance which he attributed to contemporary testimony, or to what passed for such with him, may have unduly biassed his judgment in both directions. As it happens, the authority of the canon is much weaker than Grote imagined; but even granting his extreme contention, our view of Plato’s philosophy would not be seriously affected by it, for the pieces which are rejected by all other critics have no speculative importance whatever. The case would be far different were we to agree with those who impugn the genuineness of the Parmenides, the Sophist, the Statesman, the Philêbus, and the Laws; for these compositions mark a new departure in Platonism amounting to a complete transformation of its fundamental principles, which indeed is one of the reasons why their authenticity has been denied. Apart, however, from the numerous evidences of Platonic authorship furnished by the Dialogues themselves, as well as by the indirect references to them in Aristotle’s writings, it seems utterly incredible that a thinker scarcely, if at all, inferior to the master himself—as the supposed imitator must assuredly have been—should have consented to let his reasonings pass current under a false name, and that, too, the name of one whose teaching he in some respects controverted; while there is a further difficulty in assuming that his existence could pass unnoticed at a period marked by intense literary and philosophical activity. Readers who177 wish for fuller information on the subject will find in Zeller’s pages a careful and lucid digest of the whole controversy leading to a moderately conservative conclusion. Others will doubtless be content to accept Prof. Jowett’s verdict, that ‘on the whole not a sixteenth part of the writings which pass under the name of Plato, if we exclude the works rejected by the ancients themselves, can be fairly doubted by those who are willing to allow that a considerable change and growth may have taken place in his philosophy.’116 To which we may add that the Platonic dialogues, whether the work of one or more hands, and however widely differing among themselves, together represent a single phase of thought, and are appropriately studied as a connected series. Before entering on our task, one more difficulty remains to be noticed. Plato, although the greatest master of prose composition that ever lived, and for his time a remarkably voluminous author, cherished a strong dislike for books, and even affected to regret that the art of writing had ever been invented. A man, he said, might amuse himself by putting down his ideas on paper, and might even find written178 memoranda useful for private reference, but the only instruction worth speaking of was conveyed by oral communication, which made it possible for objections unforeseen by the teacher to be freely urged and answered.117 Such had been the method of Socrates, and such was doubtless the practice of Plato himself whenever it was possible for him to set forth his philosophy by word of mouth. It has been supposed, for this reason, that the great writer did not take his own books in earnest, and wished them to be regarded as no more than the elegant recreations of a leisure hour, while his deeper and more serious thoughts were reserved for lectures and conversations, of which, beyond a few allusions in Aristotle, every record has perished. That such, however, was not the case, may be easily shown. In the first place it is evident, from the extreme pains taken by Plato to throw his philosophical expositions into conversational form, that he did not despair of providing a literary substitute for spoken dialogue. Secondly, it is a strong confirmation of this theory that Aristotle, a personal friend and pupil of Plato during many years, should so frequently refer to the Dialogues as authoritative evidences of his master’s opinions on the most important topics. And, lastly, if it can be shown that the documents in question do actually embody a comprehensive and connected view of life and of the world, we shall feel satisfied that the oral teaching of Plato, had it been preserved, would not modify in any material degree the impression conveyed by his written compositions. breakfast in the kitchen by candle-light, and then drove the five The bargaining was interminable, something in this manner:— Then follows a long discussion in Hindi with the bystanders, who always escort a foreigner in a mob, ending in the question— There was a bright I. D. blanket spread on the ground a little way back from the fire, and she threw herself down upon it. All that was picturesque in his memories of history flashed back to Cairness, as he took his place beside Landor on the log and looked at her. Boadicea might have sat so in the depths of the Icenean forests, in the light of the torches of the Druids. So the Babylonian queen might have rested in the midst of her victorious armies, or she of Palmyra, after the lion hunt in the deserts of Syria. Her eyes, red lighted beneath the shadowing lashes, met his. Then she glanced away into the blackness of the pine forest, and calling her dog to lie down beside her, stroked its silky red head. The retreat was made, and the men found themselves again in the morning on the bleak, black heath of Drummossie, hungry and worn out, yet in expectation of a battle. There was yet time to do the only wise thing—retreat into the mountains, and depend upon a guerilla warfare, in which they would have the decided advantage. Lord George Murray now earnestly proposed this, but in vain. Sir Thomas Sheridan and other officers from France grew outrageous at that proposal, contending that they could easily beat the English, as they had done at Prestonpans and Falkirk—forgetting that the Highlanders then were full of vigour and spirit. Unfortunately, Charles listened to this foolish reasoning, and the fatal die was cast. "They said they were going for our breakfast," said Harry. "And I hope it's true, for I'm hungrier'n a rip-saw. But I could put off breakfast for awhile, if they'd only bring us our guns. I hope they'll be nice Springfield rifles that'll kill a man at a mile." "Dod durn it," blubbered Pete, "I ain't cryin' bekase Pm skeered. I'm cryin' bekase I'm afeared you'll lose me. I know durned well you'll lose me yit, with all this foolin' around." He came nearly every night. If she was not at the gate he would whistle a few bars of "Rio Bay," and she would steal out as soon as she could do so without rousing suspicion. Boarzell became theirs, their accomplice in some subtle, beautiful way. There was a little hollow on the western slope where they would crouch together and sniff the apricot scent of the gorse, which was ever afterwards to be the remembrancer of their love, and watch the farmhouse lights at Castweasel gleam and gutter beside Ramstile woods. "Yes, De Boteler," continued the lady, "I will write to him, and try to soothe his humour. You think it a humiliation—I would humble myself to the meanest serf that tills your land, could I learn the fate of my child. The abbot may have power to draw from this monk what he would conceal from us; I will at least make the experiment." The lady then, though much against De Boteler's wish, penned an epistle to the abbot, in which concession and apologies were made, and a strong invitation conveyed, that he would honour Sudley castle by his presence. The parchment was then folded, and dispatched to the abbot. "A very pretty method, truly! You know not the miners and forgers of Dean Forest!—why I would stake a noble to a silver-penny, that if you had discovered he was hidden there, and legally demanded him, he would be popped down in a bucket, to the bottom of some mine, where, even the art of Master Calverley could not have dragged him to the light of day until the Forest was clear of the pack:—but, however, to speak to the point," perceiving that the steward's patience was well nigh exhausted—"I saw Stephen Holgrave yesterday, in the Forest." HoME欧美一级 片a高清
ENTER NUMBET 0016www.gxwm.net.cn www.jptech.net.cn www.hrpogg.com.cn www.eydfpx.com.cn www.iegvc.com.cn www.hyboao.com.cn rhlucz.com.cn ohrbmr.com.cn www.nwfnjt.com.cn www.nbfxj.net.cn
modal_window=true needs to be before TB_iframe in the url for this to work
This saved my day!!