I have a nav bar with categories in it. When I hover over a category I want to query the 3 most recent post using ajax.
html mark up
<ul>
<li id="alabama">Alabama</li>
<li id="banana">Banana</li>
<li id="bible">Bible</li>
</ul>
<div id="main"></div>
ajax call
$( "#alabama" ).click(function() {
var ajaxurl = "<?php echo admin_url('admin-ajax.php'); ?>";
$.post(
ajaxurl,
{
'action' : 'fetch_posts',
'fetch' : 'alabama',
},
function(output){
$('#main').html(output);
});
});
enter code here
php in functions.php
function import_post() {
if($_REQUEST['fetch'] == 'alabama'){
$query_args = array(
'post_type' => 'post',
'tax_query' => array(
'relation' => 'AND',
array(
'taxonomy' => 'category',
'field' => 'slug',
'terms' => array( 'news' ),
),
array(
'taxonomy' => 'category',
'field' => 'slug',
'terms' => array( 'alabama' ),
),
),
);
$the_query = new WP_Query( $query_args );
if ( $the_query->have_posts() ) :
while ( $the_query->have_posts() ) : $the_query->the_post();
$return_str.= '<div class="col-md-3">';
$return_str.= '<li>' . get_the_title() . '</li>';
$return_str.='</div>';
endwhile;
wp_reset_postdata();
else :
$return_str.= 'No posts found';
endif;
}
echo $return_str;
die;
}
add_action('wp_ajax_fetch_posts', 'fetch_posts');
add_action('wp_ajax_nopriv_fetch_posts', 'fetch_posts');