Skip to content

Instantly share code, notes, and snippets.

@proweb
Created July 18, 2024 21:00
Show Gist options
  • Select an option

  • Save proweb/d2c234b8250123d6db902748ba498bef to your computer and use it in GitHub Desktop.

Select an option

Save proweb/d2c234b8250123d6db902748ba498bef to your computer and use it in GitHub Desktop.

Revisions

  1. proweb created this gist Jul 18, 2024.
    50 changes: 50 additions & 0 deletions ajax.php
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,50 @@
    <?php
    // Custom AJAX Handler
    // watch https://coderwall.com/p/of7y2q/faster-ajax-for-wordpress

    /* Route functions place in functions.php or mu-plugin
    function wp_pretty_ajax()
    {
    add_rewrite_rule('ajax$', 'ajax.php', 'top');
    }
    */

    //mimic the actual admin-ajax
    define('DOING_AJAX', true);


    // AJAX Custom Handler
    ini_set('html_errors', 0);
    define('SHORTINIT', true);


    require_once __DIR__ . '/wp-load.php';

    /** For JSON Response
    $return = array(
    'message' => 'Saved',
    'ID' => 1
    );
    // https://wp-kama.ru/function/wp_send_json
    wp_send_json($return, null, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
    */

    /* For HTML Response */
    //Typical headers
    header('Content-Type: text/html');
    send_nosniff_header();

    //Disable caching
    header('Cache-Control: no-cache');
    header('Pragma: no-cache');

    //Include only the files and function we need
    require_once ABSPATH . WPINC . '/formatting.php';
    require_once ABSPATH . WPINC . '/meta.php';
    require_once ABSPATH . WPINC . '/post.php';
    wp_plugin_directory_constants();

    //and do your stuff
    // Return HTML for example for HTMX!
    echo '<h2>Hello</h2>';