When calling a PHP page with Ajax (in my WordPress theme), the PHP echo 'Hello World!';
works fine, but calling other WordPress PHP functions such as get_bloginfo();
, the function returns undefined. Is it possible to use WordPress functions inside ajax calls? What are the other options.. I know iframes may work. I am trying to load a page that outputs plugin functionality.
The error that pops up is {Fatal Error: Call to undefined function get_bloginfo() in … }
I did not test it, try some thing like below using plugin
And use JS to call plugin function to get response,
When ever you call this ajax, you will get blog information using ajax.
There’s actually a whole separate way you need to make Ajax calls within WordPress. [edit: what I mean is, there is a prescribed way; whether you need to follow it religiously or whether there are other ways to skin the cat is another story] There are tutorials aplenty (just do a websearch for “Ajax WordPress” and look for the articles that talk about implementation rather than just now Ajax is used to power its back end).
The short version is:
You should be making your calls to a particular handler, ‘admin-ajax.php’ and you should do it with a POST. You pass a data object that looks something like ‘action=someaction¶meter=foo’.
Then you should have a hook in functions.php for the “someaction” action.
There’s more to it, but I don’t think this is the best place for a tutorial. Suffice it to say, you need to delve more into it; you can’t just make an Ajax call the way you would with a straight-up markup+JavaScript page.
But it can be done. Contact forms in WP are often based on Ajax, so they might have sample code worth looking into.
WP Commands like
get_bloginfo()
should be working.Are you sure you have included all the appropriate wordpress headers (in the responding script)?
I was recently facing one similar kind of issue as I was unable to call methods with
$this->myMethod()
, and unable to access variables with$this->myVariable
. It seems like class is not being instantiated or may be the ajax method is acting like a static method so$this
has no existence within it. Though the class is being instantiated for sure as this method is being called and class constructor is also setting up things.The solution I am able to work out with is making my other variables and methods
static
, and now they were accessible byself::myMethod()
andself::$myVariable