WordPress en AJAX

  • PHP
  • Plugin
  • Snippets
  • Wordpress

Ajax betekent “Asynchronous JavaScript And XML”. Het is een term voor het ontwerp van interactieve websites waarin asynchroon gevraagde gegevens (vaak gedeeltes van websites) worden opgehaald van de webserver. Hierdoor hoeven dergelijke pagina’s niet in hun geheel ververst te worden.

Als je je bezighoudt met het ontwikkelen in WordPress zitten hier wat haken en ogen aan. (lees “AJAX in Plugins“)

Een andere techniek die (ook door WordPress zelf) gebruikt wordt is het direct aanroepen van je eigen PHP-script.

Hiervoor heb ik de onderstaande drop-in snippet gemaakt

/**
 * is_ajax_call()
 *
 * This function checks if there is an ajax-call,
 * tracks down 'wp-load.php' and includes it.
 *
 * @return boolean True if you have an ajax-call, false if not
 */
function is_ajax_call()
{
	$result = false; // Our initial return value

	// Is AJAX knocking on our door?
	if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) &&
	     strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {

		// Yes this call is AJAX, don't include wordpress-bloat
		define('SHORTINIT', true);

		// Maximum iterations (fail after this iteration)
		$max = 10;

		// Starting point to search (this directory)
		$path = dirname(__FILE__);

		// Try to find 'wp-load.php' and decrease the iteration

		while (!is_file($path . '/wp-load.php') && $max-- >= 0) {
			// Go up a directory
			$path = dirname($path);
		}

		// Check if we found the file. if not: show error and exit

		if (is_file($path . '/wp-load.php')) {

			// Include the wp-load.php file, and set the result to true
			require_once $path . '/wp-load.php';
			$result = true;

		} else {

			// We could not find wp-load.php, give 404 + error message
			header("HTTP/1.0 404 Not Found");
			die('We could not find an essential file.');

		}
	}
	return $result;
}

De snippet hierboven kijkt eerst of er een AJAX-call is gemaakt, probeert wp-load.php te vinden; indien gevonden wordt wp-load.php included. Omdat er ook een SHORTINIT wordt gedefineerd zal niet alles van wordpress worden ingeladen wat erin resulteert dat een AJAX-call met de bovenstaande functie soms wel 700% (+) aan snelheidswinst haalt.

Hoe te gebruiken?

if (is_ajax_call()) {

    // Include $wpdb
    global $wpdb;

    // Retrieve and display the number of published posts.
    $post_count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->posts WHERE post_status='publish' AND post_type='post';" );

	// Echo the HTML
	echo "<p>Your post count is {$post_count}</p>";

	// And always exit!
	exit;
}

De snippet hierboven maakt gebruik van de functie is_ajax_call. Daarna wordt het aantal van je gepubliceerde berichten opgehaald. Ik heb de bovenstaande functie expres niet in een plugin gezet zodat het makkelijk gekopieerd en geplakt kan worden, hieronder is een voorbeeld als plugin.

Een complete plugin

Hieronder is een complete plugin. Let wel! Deze plugin werkt alleen aan de administrator kant (achterkant). Wanneer deze plugin wordt geactiveerd zal deze via AJAX een bericht ophalen en weergeven hoeveel posts je hebt geplaatst op je site. Deze plugin zal dit bericht bovenaan elke pagina plakken.

<?php
/*
Plugin Name: WP Ajax Example
Plugin URI: http://www.atomicon.nl/wordpress-met-ajax
Description: This is an example on how to use wordpress along with AJAX.
Author: Yvo van Dillen
Version: 1.0
Author URI: http://www.atomicon.nl/over
*/

// ----------------------------------------------------------------------------------

/**
 * is_ajax_call()
 *
 * This function checks if there is an ajax-call,
 * tracks down 'wp-load.php' and includes it.
 *
 * @return boolean True if you have an ajax-call, false if not
 */
function is_ajax_call()
{
	$result = false; // Our initial return value

	// Is AJAX knocking on our door?
	if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) &&
	     strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {

		// Yes this call is AJAX, don't include wordpress-bloat
		define('SHORTINIT', true);

		// Maximum iterations (fail after this iteration)
		$max = 10;

		// Starting point to search (this directory)
		$path = dirname(__FILE__);

		// Try to find 'wp-load.php' and decrease the iteration

		while (!is_file($path . '/wp-load.php') && $max-- >= 0) {
			// Go up a directory
			$path = dirname($path);
		}

		// Check if we found the file. if not: show error and exit

		if (is_file($path . '/wp-load.php')) {

			// Include the wp-load.php file, and set the result to true
			require_once $path . '/wp-load.php';
			$result = true;

		} else {

			// We could not find wp-load.php, give 404 + error message
			header("HTTP/1.0 404 Not Found");
			die('We could not find an essential file.');

		}
	}
	return $result;
}

// ----------------------------------------------------------------------------------
// Here we check if it's an ajax call and handle upon it if so.

if (is_ajax_call()) {

    // Include $wpdb
    global $wpdb;

    // Retrieve and display the number of published posts.
    $post_count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->posts WHERE post_status='publish' AND post_type='post';" );

	// Echo the HTML
	echo "<p>Your post count is {$post_count}</p>";

	// And always exit!
	exit;
}

// ----------------------------------------------------------------------------------
// Here we will paste a piece of javascript code to the bottom of the admin screens

add_action( 'admin_footer', 'wp_ajax_admin_footer' );

function wp_ajax_admin_footer() { ?>

<script>
	//when the document is loaded, call the ajax plugin
	jQuery(document).ready(function($){

		$.get('<?php echo plugins_url(basename(__FILE__), __FILE__) . '?cache='. time(); ?>', function(html) {
			// here we received: <p>Your post count is ##</p>
			// we will paste the ajax to the top of the wordpress admin page

			$('#wpbody-content').prepend( html );
		});

	});
</script>

<?php
}

Installatie methode 1

  1. Kopieer de code die hierboven staat en plaats deze met FTP op je site onder: /wp-content/plugins/wp-ajax.php
  2. Log in op je site en navigeer naar: Plugins » Geïnstalleerde plugins
  3. Vrijwel onderaan in de lijst staat de plugin: “WP Ajax Example” activeer deze en de plugin zal direct zijn werk doen.

Installatie methode 2

  1. Download de plugin en sla deze op ergens op je computer.
  2. Log in op je site en navigeer naar: Plugins » Nieuwe plugin » Uploaden
  3. Selecteer de plugin die je net heeft ge-download en kies “Installeren”
  4. Navigeer naar: Plugins » Geïnstalleerde plugins
  5. Vrijwel onderaan in de lijst staat de plugin: “WP Ajax Example” activeer deze en de plugin zal direct zijn werk doen.

Geef een reactie

Het e-mailadres wordt niet gepubliceerd. Vereiste velden zijn gemarkeerd met *