Nyx

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.

PHPThe language WordPress is written in. It runs on the server, never in the browser.
DatabaseWhere WordPress keeps posts, pages, users and settings.
ThemeDecides how the site looks. It's a folder of PHP, CSS and JavaScript files.
PluginA folder of code that adds a feature, like a contact form. Nyx comes as a plugin.

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.

  1. Make a zipDownload Nyx and compress the wordpress/nyx folder into nyx.zip.
  2. Upload itIn your WordPress dashboard, go to Plugins → Add New Plugin → Upload Plugin, choose nyx.zip and click Install Now.
  3. 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:

PlaceWhen to use it
A Custom HTML blockQuick tests and small things on one page. Easiest, but only Administrators can add a <script>; for other users WordPress removes it.
Your theme's JavaScript fileCode for the whole site. Use a child theme, or your changes vanish when the theme updates.
Your own small pluginCode that should keep working even if you change themes.

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();
});
Two small details that matter

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.

SettingWhat it is
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.wp request.
  • 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:

In the browser On the server Your page nyx.wp.ajax(…) WordPress admin-ajax.php → my_like_post() Database the post's likes action, nonce, post_id { likes: 13 } saves 13 new total
Your page sends the action name, the nonce and the post ID. WordPress runs your PHP function, which saves the new total and sends back the answer.

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 ) );
}
  1. add_action( 'wp_ajax_like_post', 'my_like_post' )"When a logged-in user sends the action like_post, run my_like_post." The part after wp_ajax_ is your action name.
  2. 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.
  3. nyx_verify_request();Checks the nonce. If it's wrong or old, WordPress stops here and answers -1.
  4. absint( $_POST['post_id'] ?? 0 )$_POST['post_id'] is the post_id your JavaScript sent. absint turns it into a positive whole number, so nothing strange gets in.
  5. 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.
  6. get_post_meta / update_post_metaRead and save a value stored with the post, here called likes.
  7. wp_send_json_success( array( 'likes' => $likes ) )Sends the answer back and stops. In JavaScript it arrives as result.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:

In JavaScriptIn PHP
"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:

  1. Check the nonceStart every function with nyx_verify_request();
  2. Clean what arrivesNever use $_POST as it is. Pass each value through the right cleaning function from the table below.
  3. Check permissionFor anything only some people may do, check with current_user_can(), and don't add the nopriv line.
FunctionUse it for
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:

    PropertyWhat it holds
    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 &#8211; 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 &#8211; 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

    NyxWhat it does
    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:

    DetailWhat it does
    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.

    Only for logged-in users

    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:

    You want to...Use
    Show posts, pages or search resultsThe REST API: nyx.wp.posts(), nyx.wp.search(). No PHP needed.
    Create or edit posts as the logged-in userThe REST API: nyx.wp.post(), nyx.wp.put().
    Do your own job: a like, a form, a voteadmin-ajax: 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:

    WordPress answersWhat it means
    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

    Page cachingCaching plugins save copies of pages, nonces included. Since nonces expire after 12 to 24 hours, leave pages with AJAX out of the cache, or keep copies for less than 12 hours.
    The dashboardNyx loads on admin pages too, so you can use it in your plugin's settings screens.
    Without the pluginIf you load 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.
    A name clashIf another script already uses the name 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

      1. nyx.wp.posts({ per_page: 3, _fields: "id,title" })Get the three newest posts, with only the two properties we need.
      2. like.data("post", post.id)Make a Like button that remembers which post it belongs to.
      3. list.on("click", "button", ...)One listener on the list handles every button, even ones added later, as you learned in Events.
      4. nyx.wp.ajax("like_post", ...)Save the like with the PHP function from earlier, and show the new total.
      5. catch (error) { nyx.toast(...) }If WordPress says no, show the reason in a small message.

      Common mistakes

      MistakeFix
      It works for you, but visitors get 0You're logged in, they're not. Add the wp_ajax_nopriv_… line too.
      "nyx is not defined"Your script loaded before Nyx. Add array( 'nyx' ) to wp_enqueue_script, and check the plugin is active.
      Everything answers -1 after a dayA cache is serving an old page with an expired nonce. Leave that page out of the cache.
      Your changes vanished after a theme updateYou edited the theme itself. Put your code in a child theme or a small plugin.
      Your <script> disappears from a blockOnly Administrators may add scripts in a Custom HTML block. Use a theme file instead.
      Your edits to site.js don't show upThe browser kept an old copy. Raise the version number in wp_enqueue_script.
      Using $_POST without cleaning itAlways pass it through 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

      WordPress builds pages with PHP on the server. Your JavaScript asks it for data with nyx.wp.
      Put site-wide code in a child theme file, loaded with wp_enqueue_script and array( 'nyx' ).
      Nyx works next to jQuery and never touches $.
      nyx.wp.ajax("action", data) runs your PHP function. Add both wp_ajax_ and wp_ajax_nopriv_ lines.
      In PHP: check the nonce, clean every value, check permission, then 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).
      Nonces expire, so keep AJAX pages out of long caches. Nyx explains 0, -1 and the rest in plain English.