The idea is simple. I have a drop-down menu generated with get_categories(). This outputs a list of categories in an unordered list, each in it’s own li element.
I’m getting the text values of those li elements when a user clicks them, and based on that i want to create a custom wp_query, that returns posts from that category only. To do this, i`m loading the text value of the list element into a JS variable, send it over to a php file for processing. That php file constructs the string like so:
$ff_query = new WP_Query('posts_per_page=2&category_name='.$_POST['JSvariable']);
⦠and ideally should execute it, returning the info from the DB. The error i get is:
“Fatal error: Class ‘WP_Query’ not found in C:xampphtdocssuplywp-contentthemessuplyincludesproc_cat.php on line 3“
This is what my 2 files look like:
1) file that sends the ajax request:
<script>
$(document).ready(function(e) {
$("#ddmenu li").on('click', function() {
var cValue = $(this).text();
$.post("<?php bloginfo('template_url');?>/includes/proc_cat.php", {name: cValue}, function(cat){
alert(cat);
$(".browse-big-slider").append(cat);
});//end of post
});//end of click
});//end of ready
</script>
2) file that should process the
if(isset($_POST)){
$name = 'posts_per_page=2&category_name='.$_POST['name'];
$ff_query = new WP_Query('posts_per_page=2&category_name='.$_POST['name']);
something else, but it won`t reach this part.
}
What can i do to make this work? Or as an alternative, how can i create the type of functionality i want? (basically, a different query, generated dynamically, based on a user selection).
That’s because when calling a theme template directly you only have what’s included/defined in the template file, not the whole WordPress environment.
Some people attempt to fix this by adding an include of wp-header or load etc but this is incredibly damaging
When doing AJAX requests, never call a file in the theme, instead call the WP AJAX APIs.
With the WP AJAX API your file becomes a simple function in
functions.php
.I strongly suggest you follow the advice of this article:
http://www.garyc40.com/2010/03/5-tips-for-using-ajax-in-wordpress/#js-global
e.g.
PHP:
JS: