Create a WordPress AJAX CRUD Plugin with PHP & JS

Building a custom WordPress plugin to handle full Create, Read, Update, Delete operations via AJAX can streamline data management on the front end. This guide walks you through setting up the database table, registering secure AJAX actions with wp_ajax, and integrating JavaScript for seamless CRUD requests. Follow along for complete code snippets and best practices.

How do I make my site multilingual?

To set up a multilingual WordPress site, you’ll rely on plugins since WordPress doesn’t include built-in multilingual support. Here’s an overview:

  1. One language per post:
  2. Assign each post a language and link translations.
  3. Pros: Easy to install and remove; Cons: Database grows and architecture is more complex.
  4. All languages in one post:
  5. Store translations together with language meta tags.
  6. Pros: Convenient side-by-side editing; Cons: Harder to uninstall and permalinks aren’t language-specific.
  7. Manage translations on the page output:
  8. Use machine translation or similar on the front end.
  9. Pros: Quick setup and simple editing; Cons: Quality may vary and updates can break translations.
  10. Separate installs for each language:
  11. Run a multisite install with a site per language.
  12. Pros: Independent sites; Cons: More setup and ongoing maintenance.

Choosing a plugin depends on your needs. Browse the WordPress Plugin Directory for multilingual options, test on a staging site, and always back up your database first. You’ll typically add the language to URLs (query parameter, subdirectory, or subdomain). For more detail, see the official Multilingual WordPress guide. If you’d rather have experts help, consider a professional consultancy.

Give me the code for a fully ajax crud plugin in wordpress

Step 1: Plugin setup

Create a folder wp-content/plugins/ajax-crud-plugin, and inside it a file ajax-crud-plugin.php:

<?php
/**
 * Plugin Name: AJAX CRUD Plugin
 * Description: Simple AJAX-powered CRUD.
 * Version: 1.0
 * Author: Your Name
 */

function acp_enqueue() {
    wp_enqueue_script(
        'acp-js',
        plugins_url('js/ajax-crud.js', __FILE__),
        ['jquery'],
        null,
        true
    );
    wp_localize_script('acp-js', 'acpData', [
        'ajaxurl' => admin_url('admin-ajax.php'),
        'nonce'   => wp_create_nonce('acp_nonce'),
    ]);
}
add_action('wp_enqueue_scripts', 'acp_enqueue');

function acp_create_table() {
    global $wpdb;
    $table   = $wpdb->prefix . 'acp';
    $charset = $wpdb->get_charset_collate();

    $sql = "CREATE TABLE $table (
        id     mediumint(9) NOT NULL AUTO_INCREMENT,
        name   tinytext      NOT NULL,
        email  varchar(100)  NOT NULL,
        PRIMARY KEY  (id)
    ) $charset;";

    require_once ABSPATH . 'wp-admin/includes/upgrade.php';
    dbDelta($sql);
}
register_activation_hook(__FILE__, 'acp_create_table');

function acp_ajax() {
    check_ajax_referer('acp_nonce', 'nonce');

    global $wpdb;
    $table    = $wpdb->prefix . 'acp';
    $type     = sanitize_text_field($_POST['type']);
    $response = [];

    if ($type === 'create') {
        $ok = $wpdb->insert($table, [
            'name'  => sanitize_text_field($_POST['name']),
            'email' => sanitize_email($_POST['email']),
        ]);
        $response['status'] = $ok ? 'success' : 'error';

    } elseif ($type === 'read') {
        $response['data'] = $wpdb->get_results("SELECT * FROM $table");

    } elseif ($type === 'update') {
        $ok = $wpdb->update(
            $table,
            [
                'name'  => sanitize_text_field($_POST['name']),
                'email' => sanitize_email($_POST['email']),
            ],
            ['id' => intval($_POST['id'])]
        );
        $response['status'] = $ok !== false ? 'success' : 'error';

    } elseif ($type === 'delete') {
        $ok = $wpdb->delete($table, ['id' => intval($_POST['id'])]);
        $response['status'] = $ok ? 'success' : 'error';
    }

    wp_send_json($response);
}
add_action('wp_ajax_acp_action', 'acp_ajax');
add_action('wp_ajax_nopriv_acp_action', 'acp_ajax');

Step 2: JS file

Save this as wp-content/plugins/ajax-crud-plugin/js/ajax-crud.js:

jQuery($ => {
  $('#crud-form').submit(e => {
    e.preventDefault();
    const data = {
      action: 'acp_action',
      type:   $('#type').val(),
      name:   $('#name').val(),
      email:  $('#email').val(),
      id:     $('#id').val(),
      nonce:  acpData.nonce
    };

    $.post(acpData.ajaxurl, data, res => {
      if (res.status === 'success') {
        alert('Done!');
      } else {
        alert('Oops!');
      }
    });
  });

  $('#fetch-data').click(() => {
    $.post(
      acpData.ajaxurl,
      { action: 'acp_action', type: 'read', nonce: acpData.nonce },
      res => {
        $('#data-container').empty();
        (res.data || []).forEach(item => {
          $('#data-container').append(
            `<div>${item.id}: ${item.name} (${item.email})</div>`
          );
        });
      }
    );
  });
});

Step 3: Simple HTML form

<form id="crud-form">
  <input type="hidden" id="type" value="create">
  <input type="hidden" id="id" value="">
  <label>
    Name: <input type="text" id="name">
  </label>
  <label>
    Email: <input type="email" id="email">
  </label>
  <button type="submit">Submit</button>
</form>

<button id="fetch-data">Fetch Data</button>
<div id="data-container"></div>

Need human WordPress help?

WP Assistant is a free tool created by Atiba Software, a WordPress design and development company located in Nashville, TN. If you need more personalized WordPress assistance let us know, and we’ll get back to you ASAP!