WordPress Tip #1 : Custom Scripts, AJAX Calls, Limitless Shoddy Code …

  Jason wrote this on Jul 02 2014 / 0 comments




So you have a WordPress site and you need to save some information from the front-end, count likes, custom analytic, shit I dunno.

There comes a time in every person’s CMS career where you start realising that installing more and more plugins just causes more and more headaches, so you go in search of the coding tricks that will last more then a few core updates.

The first problem one has trying to write their own custom scripts is that you want to access the WordPress database. So you create a custom php file, include some random WordPress files till you get a connection. You know it looks ugly, but how the hell else are ya suppose to do it?

Well for one you could just go here and read up on it: WordPress Codex

But I’m gonna help you out, here it is.

First up, we need to create a function in wordpress. This will be your script. Write in it whatever the hell you want. Update a meta field (Custom Field) or return a set of results in json format. Its up to you.

The PHP: functions.php

function yourCustomFunction() {
  $stuff = $_POST['whatever']; //example for maybe forms???
  /* 
    Code whatever you want here 
  */
  
  echo $stuff; //This will be whats returned to your ajax request
  die();
}
add_action( 'wp_ajax_nopriv_yourCustomFunction', 'yourCustomFunction' );
add_action( 'wp_ajax_yourCustomFunction', 'yourCustomFunction' );

The Javascript:

jQuery(document).ready(function($) {
  var data = {
    'action': 'yourCustomFunction',
    'whatever': 1234
  };
  // since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php
  $.post(ajaxurl, data, function(response) {
    alert('Got this from the server: ' + response);
  });
});

Note: If your javascript is having trouble change ajaxurl to “/wp-admin/admin-ajax.php”

Have fun storming the castle.

This piece is tagged in...

tips (1)

Drop a Note