rainerbrunotte
rainerbrunotte

Reputation: 907

WP call custom AJAX request (WP Query) within separate PHP file

I am trying to call a custom AJAX function in a PHP file which is located inside my WP theme folder, however I cannot get it to retreive the output. I believe the issue lies in linking the WP query to the main WP files?

$.ajax({
url: "../../ajax-crew.php",
type: "POST",
data: {loadcrew: true},
etc etc etc ...

My custom ajax-crew.php file located inside my theme folder (when I simply echo out "test", I retrieve the output onto my page, but when I try to use a WP Query, it does not create any output:

<?php include '../../../wp-load.php'; ?>
<?php
if (isset($_POST['loadcrew'])){
$args = array(

'post_type' => 'team-members',
'order'     => 'rand',
'posts_per_page' => 1
);
query_posts($args);
if ( have_posts() ) : while ( have_posts() ) : the_post(); 
$thumb_id = get_post_thumbnail_id();
$thumb_url = wp_get_attachment_image_src($thumb_id,'featured-400-400', true);
$index = $wp_query->current_post;

echo $thumb_url[0];
endwhile;
endif;
} // end if isset
?>

Upvotes: 0

Views: 156

Answers (2)

sime
sime

Reputation: 7

You should try Milan's answer. But if you want to know where you code fails to return response you can use WP php console to dump variables (move your code to function.php and call function in your php script)...

Upvotes: 0

Milan Petrovic
Milan Petrovic

Reputation: 196

You should never create your own AJAX handler PHP file, it can be a security risk. WordPress has own AJAX handler file that can be hooked into using actions and filters, and you should use that instead. This article on WordPress Codex has full explanation on how to use it, and examples for front end and back end use: AJAX in Plugins.

Upvotes: 1

Related Questions