I have 2 dropdown lists, when a user select value in the first list, there is an ajax call to a function using WP_query
which send results to populate the second dropdown.
My WP_query
is not returning any result. I\'m new to WP_query
so I should have made a mistake somewhere.
The query should return the posts having the meta_key _wpcf_belongs_marque-type_id
with the meta_value equal to the parent id sent by ajax. The posts should also have the post_type \'aromes-type\'.
Here is the function located in my functions.php
:
wp_enqueue_script( \'my-ajax-request\', get_template_directory_uri() . \'/js/ajax.js\', array( \'jquery\' ) );
wp_localize_script( \'my-ajax-request\', \'MyAjax\', array( \'ajaxurl\' => admin_url( \'admin-ajax.php\' ) ) );
add_action( \'wp_ajax_brand_children\', \'GetBrandChildren\');
add_action( \'wp_ajax_nopriv_brand_children\', \'GetBrandChildren\');
function GetBrandChildren() {
$output = \'\';
//retrieve POST data sent by AJAX
$parent_id = $_GET[\'parent_id\'];
//Define query arguments
$args = array(
\'post_type\' => \'aromes-type\',
\'meta_query\' => array(
\'relation\' => \'AND\',
array(
\'key\' => \'_wpcf_belongs_marque-type_id\',
\'value\' => $parent_id
),
),
\'posts_per_page\' => -1
);
//Create the query
$the_query = new WP_Query( $args );
// The Loop
if ( $the_query->have_posts() ) :
while ( $the_query->have_posts() ) : $the_query->the_post();
$output .= \'<option>\' . get_the_title() . \'</option>\';
endwhile;
else:
$output = \'<option>No flavors found...</option>\';
endif;
echo $output;
// Reset Post Data
wp_reset_postdata();
wp_die();
}
The JQuery making the call :
//On selected brand, update flavors list
$(document).on(\'change\', "select[id^=\'marque\']", function() {
var $brandid = $(this).val();
var $brand_dd_id = $(this).attr(\'id\');
var $flav_dd_id = $brand_dd_id.substr($brand_dd_id.length-1);
//Make AJAX request, using the selected value as the GET
$.ajax({
url: MyAjax.ajaxurl,
beforeSend: function(){$("#arome"+$flav_dd_id+".ul.select2-results").empty();},
data: {
\'parent_id\': $brandid,
\'action\': \'brand_children\'
},
success: function(output) {
console.log(output);
$("#arome"+$flav_dd_id+".ul.select2-results").append(output);
$("#arome"+$flav_dd_id).trigger("chosen:updated");
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status + " "+ thrownError);
}});
});