10

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:

<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>
7
  • 2
    remove php ajax code from your code and put it into functions.php Commented Nov 26, 2013 at 8:44
  • and do I call the function or what? I don't see what you are trying to do? Commented Nov 26, 2013 at 10:18
  • Works now thanks. Got it to work when I put it in function.php Commented Nov 26, 2013 at 10:52
  • 1
    put you working code with explanation as answer which wiil help to others. Commented Dec 2, 2013 at 17:49
  • 1
    like @RavinderKumar said: You can answer your own question by taking the part starting at "Update: It works now. For future comers its this: In functions.php" and cutting it from your question and pasting it into an answer. After that, you can mark your own answer as the solution. This helps other people on the site by letting them know that you found an answer.
    – phatskat
    Commented Jan 26, 2018 at 16:10

1 Answer 1

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.