Ajax posts filter by date, comments, top views, top likes

I’m trying to create a simple Ajax posts filter, It’s working with date and comment but not working with the top views or top likes.

So, how can i make the isset( $_POST[‘top-views’] and isset( $_POST[‘top-likes’] work when I select it.

I’m highly appreciated your help.

form

<select name=”misha_order_by” id=”misha_order_by”>
<option name=”top-views” value=”top-views”>Top Views</option>
<option name=”top-likes” value=”top-likes”>Top Likes</option>
<option value=”comment_count-DESC”>Comments ↓</option>
<option value=”comment_count-ASC”>Comments ↑</option>
<option value=”date-DESC”>Date ↓</option>
<option value=”date-ASC”>Date ↑</option>
</select>

Ajax function.

add_action(‘wp_ajax_mishainsightsfilter’, ‘misha_insights_filter_function’);
add_action(‘wp_ajax_nopriv_mishainsightsfilter’, ‘misha_insights_filter_function’);

function misha_insights_filter_function(){

global $current_user;
get_currentuserinfo();

// example: date-ASC
$order = explode( ‘-‘, $_POST[‘misha_order_by’] );

$params = array(
‘posts_per_page’ => $_POST[‘misha_number_of_results’], // when set to -1, it shows all posts
‘author’ => $current_user->ID,
‘orderby’ => $order[0], // example: date
‘order’ => $order[1] // example: ASC
);

if( isset( $_POST[‘top-views’] ) )
$params = array(
‘author’ => $current_user->ID,
‘meta_key’ => ‘post_views_count’,
‘orderby’ => ‘meta_value_num’,
‘order’ => ‘DESC’
);

if( isset( $_POST[‘top-likes’] ) )
$params = array(
‘author’ => $current_user->ID,
‘meta_key’ => ‘_post_like_count’,
‘orderby’ => ‘meta_value_num’,
‘order’ => ‘DESC’
);

query_posts( $params );

global $wp_query;

if( have_posts() ) :

ob_start(); // start buffering because we do not need to print the posts now

while( have_posts() ): the_post();

the_title();

endwhile;

$posts_html = ob_get_contents(); // we pass the posts to variable
ob_end_clean(); // clear the buffer
else:
$posts_html = ‘<p>Nothing found for your criteria.</p>’;
endif;

// no wp_reset_query() required

echo json_encode( array(
‘posts’ => json_encode( $wp_query->query_vars ),
‘max_page’ => $wp_query->max_num_pages,
‘found_posts’ => $wp_query->found_posts,
‘content’ => $posts_html
) );

die();
}

Read more here:: Ajax posts filter by date, comments, top views, top likes

Leave a Reply

Your email address will not be published. Required fields are marked *