简体   繁体   中英

Filter WordPress Posts with AJAX

I've been following this tutorial: http://pixelers.net/filter-wordpress-posts-by-category-with-ajax/ . and working.

I want to create a filter based on the popular and recent post. For popular post based on a lot of the post being viewed.

For "Recent" bring up the last post. For "Popular" only display post based on the number of most viewed.

在此处输入图片说明

index.php

<div class="col-sm-12">
    <ul class="post-filters">
        <li><a href="">Recent</a></li>
        <li><a href="">Popular</a></li>
    </ul>
</div>

<main id="main" class="content site-main">
    <?php $query_args = array(
            'post_type' => 'post',
            'meta_key' => 'wpb_post_views_count',
            'orderby' => 'meta_value_num',
        );
        $the_query = new WP_Query( $query_args ); 
    ?>
    <?php if ( $the_query->have_posts() ) : ?>
        <?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
            <div class="col-md-3">
                <?php get_template_part( 'template-parts/content', 'grid' ); ?>
            </div>
        <?php endwhile; ?>
        <?php wp_reset_postdata(); ?>
    <?php else : ?>
        <?php get_template_part( 'content', 'none' ); ?>
    <?php endif; ?>
</main>

ajax.php

jQuery( document ).ready( function ( $ ) {
var $mainContent = $( '#main' ),
    $cat_links = $( '.post-filters li a' );

    $cat_links.on( 'click', function ( e ) {
        e.preventDefault();
        $el = $(this);
        var value = $el.attr( "href" );
        $mainContent.animate({opacity: "0.7"}); 
        $mainContent.load(value + " #main", function(){
            $mainContent.animate({opacity: "1"});

        }); 
    }); 
});

How can I make a link recent and popular it can Clicked and filter.

Thank you.

Make your HTML Structure like this .. Keep its inner HTML blank for first time.

<div class="col-sm-12">
    <ul class="post-filters">
        <li><a href="" id="recent_posts">Recent</a></li>
        <li><a href="" id="latest_posts">Popular</a></li>
    </ul>
</div>

<main id="main" class="content site-main">

</main>

Create onclick events in footer.php of the active theme

<script type="text/javascript">

$( "#recent_posts" ).click(function() {
  var ajaxurl = "<?php echo admin_url('admin-ajax.php'); ?>";
      $.post(
          ajaxurl, 
          {
              'action'  :   'fetch_posts',
              'fetch' :   'recent_posts',
          }, 
          function(output){
            $('#main').html(output);
          });
});

$( "#latest_posts" ).click(function() {
  var ajaxurl = "<?php echo admin_url('admin-ajax.php'); ?>";
      $.post(
          ajaxurl, 
          {
              'action'  :   'fetch_posts',
              'fetch' :   'latest_posts',
          }, 
          function(output){

          });
});


</script>

Put the below code to start coding in the functions.php of active theme

add_action('wp_ajax_fetch_posts', 'fetch_posts');

add_action('wp_ajax_nopriv_fetch_posts', 'fetch_posts');


function import_map_landing() {
    if($_REQUEST['fetch'] == 'latest_posts'){
        $query_args = array(
                'post_type' => 'post',
                'meta_key' => 'wpb_post_views_count',
                'orderby' => 'meta_value_num',
            );
            $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.=//paste the content of content-grid template here 
                $return_str.='</div>';
            endwhile;
            wp_reset_postdata();
            else :
                $return_str.= 'No posts found'
        endif;
    } 
    if($_REQUEST['fetch'] == 'recent_posts'){
        //do the code for recent posts here 
        //need to be concatinated in $return_str 
    }

    echo $return_str;
    die;
}
?>

We are concatinating all the output (php code and HTML) in the $return_str and it is echoed at the end . so please dont forget to concatinate .

Templates part needs to be pasted here not to be included

Like this <?php get_template_part( 'template-parts/content', 'grid' ); ?> <?php get_template_part( 'template-parts/content', 'grid' ); ?> needs to be replaced with the code inside this page.

Also at the start of the page we can fire the onclick event onload() to get the data on page load

For EG

$( body ).load(function() {
   var ajaxurl = "<?php echo admin_url('admin-ajax.php'); ?>";
          $.post(
              ajaxurl, 
              {
                  'action'  :   'fetch_posts',
                  'fetch' :   'recent_posts',
              }, 
              function(output){
                $('#main').html(output);
              });
});

I have called the recent_posts funtion on page load , you can switch to latest_posts as per your choice

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM