I have a script that I’d like to call via AJAX from my WordPress theme, it relies upon some core WordPress functions so I am including WordPress blog header like so:
define( 'WP_USE_THEMES', false );
require( '../../../../wp-blog-header.php' );
Somewhere during the processing of wp-blog-header.php
WordPress sets a 404 header which causes my AJAX request to fail, even though the script I am calling exists and is returning content.
I have since added status_header( 200 );
after that snippet which changes the status header back to 200 and solves the problem, however it feels very much like a hack, so I was just wondering if there is a recommended solution to this problem?
You should be including
wp-load.php
, notwp-blog-header.php
(which is reserved for use by WordPress only). This is most likely the cause of your problem.Yes there is a recommend solution for using WordPress Function via AJAX and that is using the
wp_ajax
hooks. you can see a very detailed example in my answer to “What’s the preferred method of writing AJAX-enabled plugins?”Instead of including WordPress inside of ‘Solution A’, have you considered doing it the other way around, using the vastly superior/easier WP AJAX API and then including ‘Solution A’ inside WordPress?
Calling in wp-blog-header.php for AJAX is a massive mistake, I can’t stress how big a headache you’re introducing, security and maintenance wise ( e.g. this question demonstrates some of that )
What’s the preferred method of writing AJAX-enabled plugins?
Also include
wp-load.php
notwp-blog-header.php