Add Admin JavaScript

Описание

Ever want to introduce custom dynamic functionality to your WordPress admin pages and otherwise harness the power of JavaScript? Any modification you may want to do with JavaScript can be facilitated via this plugin.

Using this plugin you’ll easily be able to define additional JavaScript (inline and/or by URL) to be added to all administration pages. You can define JavaScript to appear inline in the admin head, admin footer (recommended), or in the admin footer within a jQuery jQuery(document).ready(function($)) {} section, or reference JavaScript files to be linked in the page header. The referenced JavaScript files will appear in the admin head first, listed in the order defined in the plugin’s settings. Then any inline admin head JavaScript is added to the admin head. All values can be filtered for advanced customization (see Filters section).

Links: Plugin Homepage | Plugin Directory Page | GitHub | Author Homepage

Hooks

The plugin exposes four filters for hooking. Typically, code making use of filters should ideally be put into a mu-plugin or site-specific plugin (which is beyond the scope of this readme to explain). Bear in mind that most of the features controlled by these filters are configurable via the plugin’s settings page. These filters are likely only of interest to advanced users able to code.

c2c_add_admin_js_files (filter)

The ‘c2c_add_admin_js_files’ filter allows programmatic modification of the list of JavaScript files to enqueue in the admin.

Аргументы:

  • $files (array): Array of JavaScript files.

Например:

/**
 * Adds a JavaScript file to be enqueued in the WP admin.
 *
 * @param array $files Array of files.
 * @return array
 */
function my_admin_js_files( $files ) {
    $files[] = 'http://ajax.googleapis.com/ajax/libs/yui/2.8.1/build/yuiloader/yuiloader-min.js';
    return $files;
}
add_filter( 'c2c_add_admin_js_files', 'my_admin_js_files' );

c2c_add_admin_js_head (filter)

The ‘c2c_add_admin_js_head’ filter allows customization of the JavaScript that should be added directly to the admin page head.

Аргументы:

  • $js (string): JavaScript code (without <script> tags).

Например:

/**
 * Adds JavaScript code to be added to the admin page head.
 *
 * @param string $js JavaScript code.
 * @return string
 */
function my_add_head_js( $js ) {
    $js .= "alert('Hello');";
    return $js;
}
add_filter( 'c2c_add_admin_js_head', 'my_add_head_js' );

c2c_add_admin_js_footer (filter)

The ‘c2c_add_admin_js_footer’ filter allows customization of the JavaScript that should be added directly to the admin footer.

Аргументы:

  • $js (string): JavaScript code (without <script> tags).

Например:

/**
 * Adds JavaScript code to be added to the admin footer.
 *
 * @param string $js JavaScript code.
 * @return string
 */
function my_add_footer_js( $js ) {
    $js .= "alert('Hello');";
    return $js;
}
add_filter( 'c2c_add_admin_js_footer', 'my_add_footer_js' );

c2c_add_admin_js_jq (filter)

The ‘c2c_add_admin_js_jq’ filter allows customization of the JavaScript that should be added directly to the admin footer within a jQuery document ready function.

Аргументы:

  • $jq_js (string): JavaScript code (without <script> tags or jQuery document ready function).

Например:

/**
 * Adds jQuery code to be added to the admin footer.
 *
 * @param string $jq_js jQuery code.
 * @return string
 */
function my_add_jq( $js_jq ) {
    $js_jq .= "$('.hide_me').hide();";
    return $js_jq;
}
add_filter( 'c2c_add_admin_js_jq', 'my_add_jq' );

Highlights:

  • This minor release adds support for themes that don’t explicitly support HTML5, tweaks plugin initialization, modernizes and fixes unit tests, and notes compatibility through WP 5.3+.

Details:

  • New: Add non-HTML5 compliance by specifying type attribute when the theme doesn’t explicitly support ‘html5’
  • Change: Check that code is running in the admin just before registering hooks and not before defining class
  • Unit tests:
    • New: Add unit tests for recovery mode’s admin notice
    • New: Add assertion that recovery mode is not enabled if query param is present but false
    • Fix: Don’t pass argument to plugin object’s add_js_to_head() and add_js_to_food(), which don’t support arguments
    • Fix: Prevent WP from attempting to print the emoji detection script (which isn’t built in the develop.svn repo)
    • Change: Update unit test install script and bootstrap to use latest WP unit test repo
    • Change: Ensure admin mode is enabled before running certain tests
    • Change: Rename test_can_show_js_with_false_query_param() to test_can_show_js_with_true_query_param() to better reflect its intent
    • Change: Use dirname() instead of relative path syntax
    • Change: Remove unnecessary action performed during teardown
  • Change: Note compatibility through WP 5.3+
  • Change: Tweak installation instruction
  • Change: Tweak description of «Hooks» section in readme.txt
  • Change: Update copyright date (2020)

Full changelog is available in CHANGELOG.md.

Скриншоты

  • A screenshot of the plugin's admin settings page.

Установка

  1. Install via the built-in WordPress plugin installer. Or download and unzip add-admin-javascript.zip inside the plugins directory for your site (typically wp-content/plugins/)
  2. Activate the plugin through the ‘Plugins’ admin menu in WordPress
  3. Go to «Settings» -> «Admin JavaScript» and add some JavaScript to be added into all admin pages. (You can also use the «Settings» link in the plugin’s entry on the admin «Plugins» page).

Часто задаваемые вопросы

How can I edit the plugin’s settings in the event I supplied JavaScript that prevents the admin pages from properly loading or being seen?

It is certainly possible that you can put yourself in an unfortunate position by supplying JavaScript that could render the admin (in whole or in part) inoperable or hidden, making it seeminly impossible to fix or revert your changes. Fortunately, there are a number of approaches you can take to correct the problem.

The recommended approach is to visit the URL for the plugin’s settings page, but appended with a special query parameter to disable the output of its JavaScript. The plugin’s settings page would typically be at a URL like https://example.com/wp-admin/options-general.php?page=add-admin-javascript%2Fadd-admin-javascript.php. Append &c2c-no-js=1 to that, so that the URL is https://example.com/wp-admin/options-general.php?page=add-admin-javascript%2Fadd-admin-javascript.php&c2c-no-js=1 (obviously change example.com with the domain name for your site).

There are other approaches you can use, though they require direct database or server filesystem access:

  • Disable JavaScript in your browser and revist the page. With JavaScript disabled, any JavaScript defined by the plugin would have no effect for you. Fix the JavaScript you defined and then re-enabled JavaScript for your browser.
  • In the site’s wp-config.php file, define a constant to disable output of the plugin-defined JavaScript: define( 'C2C_ADD_ADMIN_JAVASCRIPT_DISABLED', true );. You can then visit the site’s admin. Just remember to remove that line after you’ve fixed the JavaScript (or at least change «true» to «false»). This is an alternative to the query parameter approach described above, though it persists while the constant remains defined. There will be an admin notice on the plugin’s setting page to alert you to the fact that the constant is defined and effectively disabling the plugin from adding any JavaScript.
  • Presuming you know how to directly access the database: within the site’s database, find the row with the option_name field value of c2c_add_admin_javascript and delete that row. The settings you saved for the plugin will be deleted and it will be like you’ve installed the plugin for the first time.
  • If your server has WP-CLI installed, you can delete the plugin’s setting from the commandline: wp option delete c2c_add_admin_javascript

The initial reaction by some might be to remove the plugin from the server’s filesystem. This will certainly disable the plugin and prevent the JavaScript you configured through it from taking effect, restoring the access and functionality to the backend. However, reinstalling the plugin will put you back into the original predicament because the plugin will use the previously-configured settings, which wouldn’t have changed.

Can I add JavaScript I defined via a file, or one that is hosted elsewhere?

Yes, via the «Admin JavaScript Files» input field on the plugin’s settings page.

Can I limit what admin pages the JavaScript gets output on?

No, not presently. At least not directly. By default, the JavaScript is added to every admin page on the site.

However, you can preface your selectors with admin page specific class(es) on ‘body’ tag to ensure CSS only applies on certain admin pages. (e.g. jQuery('body.index-php h2').hide();).

Or, you can hook all the plugin’s filters and determine the current admin page content to decide whether the respective hook argument should be returned (and thus output) or not.

Can I limit what users the JavaScript applies to?

No, not presently. At least not directly. By default, the JavaScript is added for any user that can enter the admin section of the site.

You can hook all the plugin’s filters and determine the current user to decide whether the respective hook argument should be returned (and thus output) for the user or not.

How do I disable syntax highlighting?

The plugin’s syntax highlighting of JavaScript (available on WP 4.9+) honors the built-in setting for whether syntax highlighting should be enabled or not.

To disable syntax highlighting, go to your profile page. Next to «Syntax Highlighting», click the checkbox labeled «Disable syntax highlighting when editing code». Note that this checkbox disables syntax highlighting throughout the admin interface and not just specifically for the plugin’s settings page.

Does this plugin include unit tests?

Да.

Отзывы

06.02.2017
I was looking for a way of adding my own simple JS code into WP admin, without getting into system files, messing things up and what not. As I was looking for this online, I quickly came across this plugin, and it does exactly what I was looking for, no huss, no fuss. Well done for this plugin! Two thumbs up!
03.09.2016
It crashed WordPress 4.5 by: Fatal error: Call to undefined function get_userdata() in /public_html/wp-includes/user.php on line 458
Посмотреть все 4 отзыва

Участники и разработчики

«Add Admin JavaScript» — проект с открытым исходным кодом. В развитие плагина внесли свой вклад следующие участники:

Участники

Перевести «Add Admin JavaScript» на ваш язык.

Заинтересованы в разработке?

Посмотрите код, проверьте SVN репозиторий, или подпишитесь на журнал разработки по RSS.

Журнал изменений

1.8.1 (2019-12-07)

  • Fix: Fix typo causing PHP warning. Props jhogervorst.

1.8 (2019-12-06)