AdamJones
AdamJones

Reputation: 601

wordpress ajax for a plugin only works when defined in the active theme

I'm testing with very simple code to try and get ajax working from within a plugin I'm writing. However I always get the dreaded 0 returned from the admin-ajax.php file.

The basic code defined in my plugins main php file is:

// Init custom actions
add_action( 'wp_ajax_import_run', 'import_run' );

function import_run() {
echo "testing 123";
die();
}

And then import_run is the action parameter parsed via the jquery ajax call.

Now the funny thing is, this works fine when I place the above php code in the themes main function.php file, but whenever I place the code in the actual plugin where it's needed it won't work. The issue is it needs to be in the plugin, not the theme.

So it seems I'm missing some small vital step about where to put my add action and function within the plugin. Any ideas?

Upvotes: 0

Views: 158

Answers (2)

AdamJones
AdamJones

Reputation: 601

I've worked out what was going on. I was adding the add_action hook everywhere but in the core root plugin page. Previously I had been adding it to a secondary php file that I thought was the root plugin file but wasn't.

The confusion occurred because I'm using a boilerplate empty plugin template to work with, so even though the plugin does very little so far its actually full of code and remarks already.

Upvotes: 0

Mahesh Budeti
Mahesh Budeti

Reputation: 394

you haven't provided your complete code in your plugin.

You can't invoke plugin function using wp ajax call.

Here's a simple WP plugin code to display some text everywhere.

<?php
/**
 * @package Testplugin
 */
/*
Plugin Name: Testplugin
Plugin URI: someuri
Description:  To demo a simple plugin
Version: 2.5.8
Author: Automattic
Author URI: http://automattic.com/wordpress-plugins/
License: GPLv2 or later
*/

function pluginnamehere() {
echo "This gets displayed everywhere";

}
add_action( 'plugins_loaded', 'pluginnamehere' );

Upvotes: 0

Related Questions