I'm trying to load post with ajax using a variable to get posts by year. I've found this great tutorial https://www.creare.co.uk/blog/simple-wp_query-ajax and I'm trying to modify it to my needs but I have 0 experience with Ajax and not so much with jquery...
this is my modified code but the year is not passed and I don't know how to do it, I appreciate any help
js
//If input is changed, load posts
$('#genre-filter input').live('change', function(){
genre_get_posts(); //Load Posts
});
//Find Selected Genres
function getSelectedGenres()
{
var genres = [];
$("#genre-filter div").click(function() {
var genres = $(this).attr('value');
console.log(genres);
});
return genres;
}
//Main ajax function
function genre_get_posts(paged)
{
var ajax_url = ajax_genre_params.ajax_url;
$.ajax({
type: 'GET',
url: ajax_url,
data: {
action: 'genre_filter',
genres: getSelectedGenres,
},
beforeSend: function ()
{
//Show loader here
},
success: function(data)
{
//Hide loader here
$('#genre-results').html(data);
},
error: function()
{
$("#genre-results").html('<p>There has been an error</p>');
}
});
}
template
<section id="primary" class="content-area">
<div id="content" class="site-content" role="main">
<?php
if ( have_posts() ):
while ( have_posts() ): the_post();
get_template_part( 'content' );
endwhile;
endif;
?>
<div class="entry-content">
<div id="genre-filter">
<div id="2018" value="2018" name="filter_genre[]">2018</div>
<div id="2017" value="2017" name="filter_genre[]">2017</div>
</div>
<div id="genre-results"></div>
</div>
</div>
functions.php
function ajax_genre_filter() {
$query_data = $_GET;
$genre_terms = ( $query_data[ 'genres' ] ) ? explode( ',', $query_data[ 'genres' ] ) : false;
$book_args = array(
'post_type' => 'book',
'posts_per_page' => 2,
'year' => $genre_terms,
);
$book_loop = new WP_Query( $book_args );
if ( $book_loop->have_posts() ):
while ( $book_loop->have_posts() ): $book_loop->the_post();
get_template_part( 'content' );
endwhile;
echo $query_data;
else :
get_template_part( 'content-none' );
endif;
wp_reset_postdata();
die();
}