I have been trying to work on a function coupled with an ajax call to pull posts based on the id of the link being clicked. That ID would in turn be the author id, so it would pull posts by that author id.
Below is what I've got set up in my functions.php file:
function ajax_filter_posts_scripts() {
// Enqueue script
wp_register_script('afp_script', get_template_directory_uri() . '/tuts/ajax-filter-posts/ajax-filter-posts.js', false, null, false);
wp_enqueue_script('afp_script');
wp_localize_script( 'afp_script', 'afp_vars', array(
'afp_nonce' => wp_create_nonce( 'afp_nonce' ), // Create nonce which we later will use to verify AJAX request
'afp_ajax_url' => admin_url( 'admin-ajax.php' ),
)
);
}
add_action('wp_enqueue_scripts', 'ajax_filter_posts_scripts', 100);
function ajax_filter_get_posts( $talent ) {
// Verify nonce
if( !isset( $_POST['afp_nonce'] ) || !wp_verify_nonce( $_POST['afp_nonce'], 'afp_nonce' ) )
die('Permission denied');
$talent = $_POST['talent'];
// WP Query
$args = array(
'author' => $talent,
'post_type' => 'roleplays', // Post type
'posts_per_page' => 10,
);
$query = new WP_Query( $args );
if ( $query->have_posts() ) : while ( $query->have_posts() ) : $query->the_post(); ?>
<h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
<?php the_excerpt(); ?>
<?php endwhile; ?>
<?php else: ?>
<h2>No posts found</h2>
<?php endif;
die();
}
add_action('wp_ajax_filter_posts', 'ajax_filter_get_posts');
add_action('wp_ajax_nopriv_filter_posts', 'ajax_filter_get_posts');
And then the following is my jquery/ajax script:
$('.filter').click( function(event) {
// Prevent defualt action - opening tag page
if (event.preventDefault) {
event.preventDefault();
} else {
event.returnValue = false;
}
// Get tag slug from title attirbute
var id = $(this).attr('id');
$('#nexus').fadeOut();
var data = {
action: 'filter_posts',
afp_nonce: afp_vars.afp_nonce,
talent: id,
};
$.ajax({
type: 'post',
dataType: 'json',
url: afp_vars.afp_ajax_url,
data: data,
success: function( data, textStatus, XMLHttpRequest ) {
$('#nexus').html( data.response );
$('#nexus').fadeIn();
/*console.log( data );
console.log( XMLHttpRequest );*/
},
error: function( MLHttpRequest, textStatus, errorThrown ) {
/*console.log( MLHttpRequest );
console.log( textStatus );
console.log( errorThrown );*/
$('#nexus').html( 'No posts found' );
$('#nexus').fadeIn();
}
})
});
I just can't seem to get any of it to talk to one another, and I'm not sure where I'm going wrong. I essentially want to be able to click a link, and have it pull posts based on the ID of the link and return them in a listing of posts per my function.
Any ideas?