Chapter 10 · Core
Using Nyx in WordPress
WordPress runs a huge share of the world's websites, so sooner or later you'll want your JavaScript on one. In this chapter you'll install Nyx in WordPress, learn where your code goes, and make WordPress save and send data: a Like button, a newsletter form, a list of the latest posts and more.
How WordPress makes a page
A plain HTML file is sent to the browser as it is. WordPress is different: every page is built on the server when someone asks for it. A program written in PHP takes your posts from a database, puts them into your theme's layout, and sends the finished HTML to the browser.
Your JavaScript runs in the browser, after the page arrives. So when it needs to save or load something, it has to ask WordPress on the server, exactly like the AJAX in Servers and AJAX. Nyx's nyx.wp tools make that one line.
Installing Nyx
Nyx comes with a small WordPress plugin in the wordpress/nyx folder. It loads Nyx on your site and tells it where WordPress listens for requests.
- Make a zipDownload Nyx and compress the
wordpress/nyxfolder intonyx.zip. - Upload itIn your WordPress dashboard, go to Plugins → Add New Plugin → Upload Plugin, choose
nyx.zipand click Install Now. - Activate itClick Activate. Nyx now loads on every page of your site.
If you can reach your site's files (for example with FTP, or a local WordPress), you can instead copy the nyx folder into wp-content/plugins/ and activate it under Plugins.
Where your JavaScript goes
There are three good places, depending on what you're making:
<script>; for other users WordPress removes it.A Custom HTML block
Edit a page, add a Custom HTML block, and paste this. Then preview the page and click the button:
<button id="hi">Say hi</button>
<script>
nyx(() => {
nyx("#hi").on("click", () => nyx.toast("Hello from WordPress!"));
});
</script>nyx(() => { ... }) waits until the page is ready, as you learned in Getting started. The Nyx plugin loads at the bottom of the page, so this wrapper matters in WordPress.
A file in your theme
For code used across the site, make a file such as js/site.js in your child theme, and tell WordPress about it in the theme's functions.php:
add_action( 'wp_enqueue_scripts', function () {
wp_enqueue_script( 'my-site', get_theme_file_uri( 'js/site.js' ), array( 'nyx' ), '1.0', true );
} );"Enqueue" just means "add to the list of scripts on the page". Here's what each part does:
'my-site',a name you choose
get_theme_file_uri( 'js/site.js' ),where the file is
array( 'nyx' ),load Nyx first
'1.0',version
trueat the bottom of the page
Then write your Nyx code in site.js, inside the ready wrapper:
// js/site.js
nyx(() => {
nyx(".menu li").picker();
nyx(".menu a").markCurrent();
});array( 'nyx' ) makes WordPress load Nyx before your file. Leave it out and you may see "nyx is not defined". And when you change site.js, raise the version ('1.1', '1.2', ...) so visitors' browsers fetch the new copy instead of an old saved one.
Want Nyx only on pages that need it? Add add_filter( 'nyx_load_everywhere', '__return_false' ); to functions.php. Nyx then loads only where a script lists 'nyx' in its array( ... ).
Nyx next to jQuery
WordPress comes with jQuery, and many themes and plugins use it. Nyx never touches $ or jQuery, so they keep working, and your code doesn't need the special wrapper that jQuery needs in WordPress:
jQuery in WordPress
jQuery(function ($) {
$("#hi").on("click", function () {
alert("Hello");
});
});In WordPress, $ doesn't work on its own. You have to get it from this wrapper.
Nyx in WordPress
nyx(() => {
nyx("#hi").on("click", () => {
nyx.toast("Hello");
});
});Works the same everywhere: plain HTML pages and WordPress.
The practice WordPress
This website isn't a WordPress site, so, just like the practice server in Servers and AJAX, it has a small pretend WordPress built in for the examples. It has three school posts, two pages and a logged-in teacher called Asha. Your Nyx code is exactly what you'd write on a real site.
On a real site, the Nyx plugin writes a few settings into every page so that nyx.wp knows where to send requests. You can see them with nyx.wp.config():
Watch the Output below.
ajaxUrlThe address of admin-ajax.php, where your own actions go. On a real site: https://yoursite.com/wp-admin/admin-ajax.php.restUrlThe start of the REST API addresses. On a real site: https://yoursite.com/wp-json/.nonceThe security ticket for nyx.wp.ajax().restNonceThe security ticket for the REST API.You never type these yourself. Nyx reads them every time you use nyx.wp.
Nonces: the security ticket
Imagine a bad website that secretly makes your browser send "delete my posts" to your WordPress site while you're logged in. To stop that, WordPress puts a random code called a nonce into its own pages. A request must bring the nonce back, which proves it came from a page on your site, a bit like a cinema ticket that's only sold at the cinema.
- Nyx sends the nonce for you with every
nyx.wprequest. - Your PHP checks it with one line:
nyx_verify_request(); - Nonces expire after 12 to 24 hours. A page left open, or kept by a cache for too long, carries an old ticket, and WordPress refuses it.
Saving data with admin-ajax
Let's build a Like button that saves without reloading. WordPress has one address for this kind of job, admin-ajax.php. You give your job a name, called an action, and write a PHP function that does it. Here's the journey of one click:
The PHP side
This goes in your child theme's functions.php, or in your own plugin:
add_action( 'wp_ajax_like_post', 'my_like_post' ); // logged-in users
add_action( 'wp_ajax_nopriv_like_post', 'my_like_post' ); // visitors
function my_like_post() {
nyx_verify_request();
$post_id = absint( $_POST['post_id'] ?? 0 );
if ( 'publish' !== get_post_status( $post_id ) ) {
wp_send_json_error( array( 'message' => 'That post does not exist.' ), 404 );
}
$likes = (int) get_post_meta( $post_id, 'likes', true ) + 1;
update_post_meta( $post_id, 'likes', $likes );
wp_send_json_success( array( 'likes' => $likes ) );
}add_action( 'wp_ajax_like_post', 'my_like_post' )"When a logged-in user sends the actionlike_post, runmy_like_post." The part afterwp_ajax_is your action name.wp_ajax_nopriv_like_postThe same, for visitors who aren't logged in. Without this line, the button works for you but not for your visitors.nyx_verify_request();Checks the nonce. If it's wrong or old, WordPress stops here and answers-1.absint( $_POST['post_id'] ?? 0 )$_POST['post_id']is thepost_idyour JavaScript sent.absintturns it into a positive whole number, so nothing strange gets in.get_post_status( $post_id )Only count likes for a real, published post. Without this check, anyone could send any number and add likes to drafts, private posts or posts that don't exist.wp_send_json_error()answers with an error and stops.get_post_meta / update_post_metaRead and save a value stored with the post, here calledlikes.wp_send_json_success( array( 'likes' => $likes ) )Sends the answer back and stops. In JavaScript it arrives asresult.likes.
The JavaScript side
nyx.wp.ajax() sends the action name, the nonce and your data, and gives you what PHP passed to wp_send_json_success. Click the buttons:
nyx.wp.ajax(ask admin-ajax.php
"like_post",the action name
{ post_id: 101 }your data
)Done
The names on both sides must match. This table shows how they connect:
"like_post"wp_ajax_like_post and wp_ajax_nopriv_like_post{ post_id: 101 }$_POST['post_id']result.likeswp_send_json_success( array( 'likes' => 13 ) )error.messagewp_send_json_error( array( 'message' => '...' ) )In your theme, the button gets the post's ID and current likes from PHP:
<button class="like" data-post="<?php the_ID(); ?>">
Like <span class="count"><?php echo (int) get_post_meta( get_the_ID(), 'likes', true ); ?></span>
</button>Sending a form to WordPress
Give nyx.wp.ajax() a form instead of an object, and it sends every field. Here's a newsletter form. Try a wrong email first, then a correct one:
novalidate on the form turns off the browser's own email check, so you can see WordPress's answer. On your own site you can leave it out.
The PHP checks the email, and uses wp_send_json_error() when something is wrong. Its message becomes error.message in JavaScript:
add_action( 'wp_ajax_subscribe', 'my_subscribe' );
add_action( 'wp_ajax_nopriv_subscribe', 'my_subscribe' );
function my_subscribe() {
nyx_verify_request();
$email = sanitize_email( $_POST['email'] ?? '' );
if ( ! is_email( $email ) ) {
wp_send_json_error( array( 'message' => 'Please enter a valid email address.' ), 400 );
}
// Save it here, for example in your newsletter plugin
wp_send_json_success( array( 'message' => "Thanks! The newsletter will go to $email." ) );
}Files too
Because the whole form is sent, file fields work as well. In PHP, a field called homework arrives as $_FILES['homework'], and WordPress can save it to the Media Library:
function my_upload_homework() {
nyx_verify_request();
if ( ! current_user_can( 'upload_files' ) ) {
wp_send_json_error( array( 'message' => 'You are not allowed to upload files.' ), 403 );
}
require_once ABSPATH . 'wp-admin/includes/image.php';
require_once ABSPATH . 'wp-admin/includes/file.php';
require_once ABSPATH . 'wp-admin/includes/media.php';
$id = media_handle_upload( 'homework', 0 );
if ( is_wp_error( $id ) ) {
wp_send_json_error( array( 'message' => $id->get_error_message() ) );
}
wp_send_json_success( array( 'url' => wp_get_attachment_url( $id ) ) );
}Keeping your PHP safe
Anyone can send anything to admin-ajax.php, not just your page. So your PHP function should follow three rules:
- Check the nonceStart every function with
nyx_verify_request(); - Clean what arrivesNever use
$_POSTas it is. Pass each value through the right cleaning function from the table below. - Check permissionFor anything only some people may do, check with
current_user_can(), and don't add thenoprivline.
absint( $value )IDs and counts: a whole number, 0 or more.sanitize_text_field( $value )One line of text, like a name. Removes HTML and line breaks.sanitize_textarea_field( $value )Longer text from a <textarea>. Keeps line breaks.sanitize_email( $value )Email addresses. Check the result with is_email().esc_url_raw( $value )Web addresses you're going to save.current_user_can( 'edit_posts' )Is this user allowed to do this? Other common checks: 'manage_options' (admins), 'upload_files'.// Only editors and admins may pin a notice, so there's no nopriv line
add_action( 'wp_ajax_pin_notice', 'my_pin_notice' );
function my_pin_notice() {
nyx_verify_request();
if ( ! current_user_can( 'edit_posts' ) ) {
wp_send_json_error( array( 'message' => 'You are not allowed to do this.' ), 403 );
}
update_option( 'pinned_notice', sanitize_text_field( $_POST['text'] ?? '' ) );
wp_send_json_success();
}Reading content with the REST API
WordPress also gives out its content as JSON at ready-made addresses, called the REST API. Open https://yoursite.com/wp-json/wp/v2/posts in a browser and you'll see your posts as data. You don't need to write any PHP to read them. Here are the three latest posts:
Each post is an object. The ones you'll use most:
post.idThe post's number.post.title.renderedThe title, ready to show as HTML.post.excerpt.renderedThe short summary, as HTML.post.linkThe address of the post's page.post.dateWhen it was published, like "2026-11-27T09:00:00".Why .html() for titles?
WordPress sends titles with special characters written as HTML codes, like – for a dash. .text() would show those codes. WordPress has already made rendered safe, so it's fine to use it as HTML:
.text()
li.text(post.title.rendered);Shows: Sports Day – Results
.html()
li.html(post.title.rendered);Shows: Sports Day – Results
This is only for WordPress's rendered values. Text typed by your visitors still goes in with .text(), as you learned in Changing content.
All the REST tools
nyx.wp.posts({ ... })Gets posts.nyx.wp.pages({ ... })Gets pages.nyx.wp.search("exam")Searches posts and pages. Each result has title, url and subtype ("post" or "page").nyx.wp.get("wp/v2/posts/101")Gets any REST address. Here: post number 101.nyx.wp.post(path, data)Creates something, like a new post.nyx.wp.put(path, data)Changes something.nyx.wp.delete(path)Deletes something.Add details in { } to choose what you get back:
per_page: 5How many to get. WordPress sends 10 if you don't say, and 100 at most.page: 2The next five, after the first five.search: "exam"Only the ones containing this word.orderby: "title"Sort by title. The default is "date", newest first.order: "asc"Reverse the order: oldest first, or A to Z._fields: "id,title"Only send these properties, which makes the answer smaller and faster.Watch the Output below.
Doing things as the logged-in user
Reading published posts works for everyone. Creating or editing content needs someone who is logged in and allowed to do it. Nyx sends the REST nonce with every request, so WordPress knows who's asking. In the practice WordPress, you're logged in as Asha, a teacher:
Watch the Output below.
Change "draft" to "later" and run it again to see how Nyx explains WordPress's rest_invalid_param error.
On a real site, this only works for a visitor who is logged in and whose role allows it: authors can create posts, but subscribers can't. For everyone else WordPress answers 401 or 403, and Nyx tells you why.
Your own REST address
You can add your own address in PHP with register_rest_route(). This one gives out the pinned notice from the earlier example:
add_action( 'rest_api_init', function () {
register_rest_route( 'school/v1', '/notice', array(
'methods' => 'GET',
'callback' => function () {
return array( 'text' => get_option( 'pinned_notice', '' ) );
},
'permission_callback' => '__return_true', // anyone may read it
) );
} );const notice = await nyx.wp.get("school/v1/notice");
nyx("#notice").text(notice.text);permission_callback decides who may use the address. '__return_true' means everyone; for something private, use a function that checks current_user_can().
admin-ajax or REST?
Both work well with Nyx. A simple rule:
nyx.wp.posts(), nyx.wp.search(). No PHP needed.nyx.wp.post(), nyx.wp.put().nyx.wp.ajax() with one PHP function. It's the easiest to start with.When WordPress says no
WordPress's own error messages are short and puzzling: a single 0, a -1, or a code like rest_no_route. Nyx translates them into plain English, with a hint on how to fix them. Run this to see one:
Watch the Output below.
Now replace the await line with each of these, one at a time, and press Run again:
// An old nonce, like a page left open overnight
await nyx.wp.ajax("like_post", { post_id: 101, nonce: "old" }, { quiet: true });
// Your PHP's own message from wp_send_json_error()
await nyx.wp.ajax("like_post", { post_id: 999 }, { quiet: true });
// A PHP warning that broke the answer
await nyx.wp.ajax("broken_like", { post_id: 101 }, { quiet: true });
// PHP that used echo and forgot to stop
await nyx.wp.ajax("old_like", { post_id: 101 }, { quiet: true });
// A typo in a REST address
await nyx.wp.get("wp/v2/post", null, { quiet: true });Here's every case Nyx explains:
0There's no PHP function for that action. Check the name, and add add_action( 'wp_ajax_…' ), plus wp_ajax_nopriv_… for visitors.-1The security check failed. The page is old or cached; reload it.<b>Warning</b>: …PHP printed a warning or error page instead of data. Nyx shows you its message, including the file and line.{ ... }0Your PHP used echo and didn't stop, so WordPress added a 0. Use wp_send_json_success() instead.wp_send_json_error()Your own message, as error.message.rest_no_routeThat REST address doesn't exist, or doesn't accept this kind of request. Check the spelling.rest_cookie_invalid_nonceThe REST nonce expired. Reload the page.rest_not_logged_inYou need to log in first.rest_forbidden, rest_cannot_createYou're logged in, but your role isn't allowed to do this.rest_invalid_paramSome data you sent isn't allowed. error.data.data.params says which.500A PHP error crashed the request ("There has been a critical error"). Turn on WP_DEBUG to see it.Seeing PHP errors
To see what PHP is complaining about, add these lines to wp-config.php, above the line that says "That's all, stop editing!". Errors are then written to wp-content/debug.log:
define( 'WP_DEBUG', true );
define( 'WP_DEBUG_LOG', true );
define( 'WP_DEBUG_DISPLAY', false );Turn WP_DEBUG back to false on a live site when you're done.
Good to know
nyx.js yourself, nyx.wp uses the usual addresses (/wp-admin/admin-ajax.php and /wp-json/), but there are no nonces, so you'd have to send them yourself. Using the plugin is easier.nyx, write const N = nyx.noConflict(); and use N instead.Putting it together
A "Latest news" box: it loads the three newest posts with the REST API, and gives each one a Like button that saves with admin-ajax:
Latest news
nyx.wp.posts({ per_page: 3, _fields: "id,title" })Get the three newest posts, with only the two properties we need.like.data("post", post.id)Make a Like button that remembers which post it belongs to.list.on("click", "button", ...)One listener on the list handles every button, even ones added later, as you learned in Events.nyx.wp.ajax("like_post", ...)Save the like with the PHP function from earlier, and show the new total.catch (error) { nyx.toast(...) }If WordPress says no, show the reason in a small message.
Common mistakes
wp_ajax_nopriv_… line too.array( 'nyx' ) to wp_enqueue_script, and check the plugin is active.wp_enqueue_script.absint(), sanitize_text_field() or another cleaning function.Exercise
Fill in the blanks, then press Check answers.
1. Make WordPress load Nyx before your script.
wp_enqueue_script( 'my-site', get_theme_file_uri( 'js/site.js' ), array( '' ), '1.0', true );
2. Send the action like_post to admin-ajax.
const result = await nyx.wp.("like_post", { post_id: 5 });
3. Let visitors who aren't logged in use the action too.
add_action( 'wp_ajax__like_post', 'my_like_post' );
4. Check the nonce in your PHP function.
();
5. Send the answer back from PHP.
wp_send_json_( array( 'likes' => $likes ) );
6. Get the five newest posts.
const posts = await nyx.wp.posts({ : 5 });
7. Show a post's title on the page.
li.html(post.title.);
Remember
nyx.wp.wp_enqueue_script and array( 'nyx' ).$.nyx.wp.ajax("action", data) runs your PHP function. Add both wp_ajax_ and wp_ajax_nopriv_ lines.wp_send_json_success() or wp_send_json_error().nyx.wp.posts(), pages() and search() read content with no PHP. Show titles with .html(post.title.rendered).0, -1 and the rest in plain English.