AJAX with loop filtering categories

I’ve been researching on how to make my loop with AJAX. I found some codes online and modified some parts but I can’t seem to get it to work.

This is my code for the loop:

Read More
<article id="main" class="five seventh padded">
<?php

$categories = get_categories(); ?>

<ul id="category-menu">
    <?php foreach ( $categories as $cat ) { ?>
    <li id="cat-<?php echo $cat->term_id; ?>"><a class="<?php echo $cat->slug; ?> ajax" onclick="cat_ajax_get('<?php echo $cat->term_id; ?>');" href="#"><?php echo $cat->name; ?></a></li>

    <?php } ?>
</ul>
<div id="loading-animation" style="display: none;"><img src="<?php echo admin_url ( 'images/loading-publish.gif' ); ?>"/></div>
<div id="category-post-content">
    <?php add_action( 'wp_ajax_nopriv_load-filter', 'prefix_load_cat_posts' );
        add_action( 'wp_ajax_load-filter', 'prefix_load_cat_posts' );
        function prefix_load_cat_posts () {
            $cat_id = $_POST[ 'cat' ];
                 $args = array (
                'cat' => $cat_id,
                'posts_per_page' => 10,
                'order' => 'DESC'

            );

            $posts = get_posts( $args );

            ob_start ();

            foreach ( $posts as $post ) {
            setup_post_data( $post ); ?>


<article class="post">
    <!-- Display the Title as a link to the Post's permalink. -->
    <h2><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></h2>
    <!-- Display the date (November 16th, 2009 format) and a link to other posts by this posts author. -->
    <div class="row pad-bottom">
    <!-- Display a comma separated list of the Post's Categories. -->
    <small class="postmetadata pull-left"><?php the_category(', '); ?></small>
    <small class="date pull-left"> Posted by <?php the_author_posts_link() ?> on <?php the_time('F jS, Y') ?></small>

    </div>
    <!-- Display the Post's content in a div box. -->
    <article id="entry">
        <?php the_content('Read More here...'); ?>
    </article>
</article> <!-- closes the first div box -->
<!-- Stop The Loop (but note the "else:" - see next line). -->
 <?php } wp_reset_postdata();

       $response = ob_get_contents();
       ob_end_clean();

       echo $response;
       die(1);
       }
       ?>

</div>
<script>
function cat_ajax_get(catID) {
    jQuery("a.ajax").removeClass("current");
    jQuery("a.ajax").addClass("current"); //adds class current to the category menu item being displayed so you can style it with css
    jQuery("#loading-animation-2").show();
    var ajaxurl = 'http://localhost/united/wp-admin/admin-ajax.php';
    jQuery.ajax({
        type: 'POST',
        url: ajaxurl,
        data: {"action": "load-filter", cat: catID },
        success: function(data) {
            console.log(data);
        }
    });
}
</script>


</article>

For some reason I do not get anything back when I click on a category. Any help would be greatly appreciated.

Update:
It works now. For future comers its this:
In functions.php

<?php add_action( 'wp_ajax_nopriv_load-filter', 'prefix_load_cat_posts' );
        add_action( 'wp_ajax_load-filter', 'prefix_load_cat_posts' );
        function prefix_load_cat_posts () {
            $cat_id = $_POST[ 'cat' ];
                 $args = array (
                'cat' => $cat_id,
                'posts_per_page' => 10,
                'order' => 'DESC'

            );

            $posts = get_posts( $args );
                    global $post;

            ob_start ();

            foreach ( $posts as $post ) {
            setup_postdata( $post ); ?>


<article class="post">
    <!-- Display the Title as a link to the Post's permalink. -->
    <h2><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></h2>
    <!-- Display the date (November 16th, 2009 format) and a link to other posts by this posts author. -->
    <div class="row pad-bottom">
    <!-- Display a comma separated list of the Post's Categories. -->
    <small class="postmetadata pull-left"><?php the_category(', '); ?></small>
    <small class="date pull-left"> Posted by <?php the_author_posts_link() ?> on <?php the_time('F jS, Y') ?></small>

    </div>
    <!-- Display the Post's content in a div box. -->
    <article id="entry">
        <?php the_content('Read More here...'); ?>
    </article>
</article> <!-- closes the first div box -->
<!-- Stop The Loop (but note the "else:" - see next line). -->
 <?php } wp_reset_postdata();

       $response = ob_get_contents();
       ob_end_clean();

       echo $response;
       die(1);
       }
       ?>

in your theme file:

<article id="main" class="five seventh padded">
<?php

$categories = get_categories(); ?>

<ul id="category-menu">
    <?php foreach ( $categories as $cat ) { ?>
    <li id="cat-<?php echo $cat->term_id; ?>"><a class="<?php echo $cat->slug; ?> ajax" onclick="cat_ajax_get('<?php echo $cat->term_id; ?>');" href="#"><?php echo $cat->name; ?></a></li>

    <?php } ?>
</ul>
<div id="loading-animation" style="display: none;"><img src="<?php echo admin_url ( 'images/loading-publish.gif' ); ?>"/></div>
<div id="category-post-content">


</div>
<script>
function cat_ajax_get(catID) {
    jQuery("a.ajax").removeClass("current");
    jQuery("a.ajax").addClass("current"); //adds class current to the category menu item being displayed so you can style it with css
    jQuery("#loading-animation-2").show();
    var ajaxurl = 'http://localhost/united/wp-admin/admin-ajax.php';
    jQuery.ajax({
        type: 'POST',
        url: ajaxurl,
        data: {"action": "load-filter", cat: catID },
        success: function(response) {
            jQuery("#category-post-content").html(response);
            jQuery("#loading-animation").hide();
            return false;
        }
    });
}
</script>


</article>

Related posts

1 comment

  1. I know this is old, this looks exactly what I need, but isn’t working ATM.

    I paste everything on functions.php for a reason.

    ONE: Category Loop for theme file: Printed it with a shortcode, because i’m using bakery I wan’t to put it in an specific place in the site. This is Working fine.

     <?php 
    
        function ajaxcatloop( $atts, $content = null ) {
    
        $categories = get_categories();  
    
        $output .= '<article id="main" class="five seventh padded">';
    
        $output .= ' <ul id="category-menu">';
    
        foreach ( $categories as $cat ) {
    
        $output .= '<li id="cat-'.$cat->term_id.'"><a class="'.$cat->slug.' ajax" onclick="cat_ajax_get("'.$cat->term_id.'");" href="#">'.$cat->name.'</a></li>';
    
        }
        $output .= '</ul>';
        $output .= '<div id="category-post-content">';
        $output .= '</div>';
        $output .= '</article>';
    
        return $output;
    
        }
    
        add_shortcode( 'loopajax', 'ajaxcatloop' );
    
         ?>
    

    TWO: The jquery code that was in theme file: In indexing it in the footer to avoid jquery issues.
    IDK if this is working, but its getting placed in its place

        <?php add_action('wp_footer', function(){ ?>
    
    <script>
    function cat_ajax_get(catID) {
        jQuery("a.ajax").removeClass("current");
        jQuery("a.ajax").addClass("current"); //adds class current to the category menu item being displayed so you can style it with css
        jQuery("#loading-animation-2").show();
        var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
        jQuery.ajax({
            type: 'POST',
            url: ajaxurl,
            data: {"action": "load-filter", cat: catID },
            success: function(response) {
                jQuery("#category-post-content").html(response);
                jQuery("#loading-animation").hide();
                return false;
            }
        });
    }
    </script>
    
    
      <?php
    });
    
    ?>
    

    THREE: Placing AJAX code where it supose to be.

        add_action( 'wp_ajax_nopriv_load-filter', 'prefix_load_cat_posts' );
            add_action( 'wp_ajax_load-filter', 'prefix_load_cat_posts' );
            function prefix_load_cat_posts () {
                $cat_id = $_POST[ 'cat' ];
                     $args = array (
                    'cat' => $cat_id,
                    'posts_per_page' => 10,
                    'order' => 'DESC'
    
                );
    
                $posts = get_posts( $args );
                        global $post;
    
                ob_start ();
    
                foreach ( $posts as $post ) {
                setup_postdata( $post ); ?>
    
    
    <article class="post">
        <!-- Display the Title as a link to the Post's permalink. -->
        <h2><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></h2>
        <!-- Display the date (November 16th, 2009 format) and a link to other posts by this posts author. -->
        <div class="row pad-bottom">
        <!-- Display a comma separated list of the Post's Categories. -->
        <small class="postmetadata pull-left"><?php the_category(', '); ?></small>
        <small class="date pull-left"> Posted by <?php the_author_posts_link() ?> on <?php the_time('F jS, Y') ?></small>
    
        </div>
        <!-- Display the Post's content in a div box. -->
        <article id="entry">
            <?php the_content('Read More here...'); ?>
        </article>
    </article> <!-- closes the first div box -->
    <!-- Stop The Loop (but note the "else:" - see next line). -->
     <?php } wp_reset_postdata();
    
           $response = ob_get_contents();
           ob_end_clean();
    
           echo $response;
           die(1);
           }
    ?>
    

    I’ve Copy the same exact code just placed in a different way of need

    But when I click one of the categories it trows me this error, in this line and nothing happens.

    <article id="main" class="five seventh padded"> <ul id="category-menu"><li id="cat-8"><a class="carnes ajax" onclick="cat_ajax_get("8");" href="#">Carnes</a></li><li id="cat-9"><a class="comida-saludable ajax" onclick="cat_ajax_get("9");" href="#">Comida Saludable</a></li><li id="cat-3"><a class="jugos ajax" onclick="cat_ajax_get("3");" href="#">Jugos</a></li></ul><div id="loading-animation" style="display: none;"><img src=""/></div><div id="category-post-content"></div></article>
    
    Uncaught Syntax Error: Unexpected end of imput
    

Comments are closed.