4

This is my first foray into AJAX, I've been splicing bits of code from various tutorials which probably hasn't helped.

I have a list of categories on my homepage (index.php) and a list of the most recent posts. When a user clicks on a category I want this list of posts to be updated without refreshing the page. Currently when I click a filter all the posts are being loaded into my response container (it's not filtering by category) and the only content being loaded in is the_content(), even though my template (listing-post.php) asks for the thumbnail, the category etc.

I'm using Bones as my starter theme, hence why wp_localize_script is in this file (it's working). I've only included code that I know has issues, (I know that the rest of the site and JS is working fine).

bones.php

//Add AJAX path to use in load-posts.js
$getPath = array('ajaxURL' => admin_url('admin-ajax.php'));
wp_localize_script('main-js', 'pathToFile', $getPath);

functions.php

//AJAX Category Filter
add_action( 'wp_ajax_load_cat_posts', 'load_cat_posts' );
add_action( 'wp_ajax_nopriv_load_cat_posts', 'load_cat_posts' );

function load_cat_posts () {
    $cat_id = get_post_meta($_REQUEST['cat']);
    $args = array (
      'cat' => $cat_id,
      'posts_per_page' => 10,
      'order' => 'DESC'
    );

    $posts = get_posts($args);

    ob_start ();

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

      <?php get_template_part( 'partials/listing', 'post'); ?>

   <?php } wp_reset_postdata();

   $response = ob_get_contents();
   ob_end_clean();

   echo $response;
   die(1);
}

index.php

<?php $categories = get_categories(); ?>

<ul class="category-filters">
    <?php foreach ( $categories as $cat ) { ?>
        <li id="cat-<?php echo $cat->term_id; ?>">
            <a class="<?php echo $cat->slug; ?> ajax" data-cat="<?php echo $cat->term_id; ?>" href="javascript:void(0)"><?php echo $cat->name; ?></a>
        </li>
    <?php } ?>
</ul>

listing-post.php

<li class="standard-post">
    <article id="<?php echo sanitize_title_with_dashes( get_the_title() ); ?>" <?php post_class(); ?> role="article">

        <?php if (has_post_thumbnail()) { ?>
            <div class="article-image">
                <?php the_post_thumbnail(large); ?>
            </div>
        <?php } ?>

        <div class="article-left">
            <?php foreach((get_the_category()) as $category) { ?>
                <span class="article-category"><?php echo $category->cat_name . ' ';?></span>
            <?php } ?>
            </div>

            <div class="article-right">
            <header class="article-header">
                <h1 class="article-title"><?php the_title(); ?></h1>
                <p class="article-time">
                    <?php printf( __( '<time class="updated" datetime="%1$s" pubdate>%2$s</time>', 'bonestheme' ), get_the_time(), get_the_time(get_option('date_format'))); ?>
                </p>
            </header>

            <section class="entry-content">
                <?php the_content(); ?>
            </section>
        </div>

    </article>
</li>

load-posts.js

function cat_ajax_get(currentCat) {
            $('a.ajax').removeClass('current');
            $('a.ajax').addClass('current');
            $('#loading-animation').show();
            $.ajax({
                type: 'POST',
                url: ajaxurl,
                data: {action: 'load_cat_posts', cat: currentCat },
                success: function(response) {
                    $('.article-listing').html(response);
                    $('#loading-animation').hide();
                    return false;
                }
            });
        };

ajaxFilters: function() {
            $('.category-filters a').on('click', $.proxy(function(clickEvent) {
                $clickTarget = $(clickEvent.currentTarget);
                var currentCat = $clickTarget.attr('data-cat');
                cat_ajax_get(currentCat);
            },this));
        }
4
  • 1
    I remember having a similar issue in the past. This is a long shot, but trying adding this to functions.php add_action('template_redirect', 'register_scripts');
    – gdaniel
    Jul 24, 2014 at 14:43
  • I'm afraid that hasn't solved the problem. Thanks for trying though. Jul 24, 2014 at 14:53
  • Before answering any more in depth, could it be the typo in add_action( 'wp_ajax_oad_cat_posts', 'load_cat_posts' ); (i.e. wp_ajax_oad should be wp_ajax_load)? Jul 24, 2014 at 14:55
  • It is, thanks very much John! I'm editing the question now as I have another issue. Jul 24, 2014 at 15:24

1 Answer 1

1

This line in functions.php is your problem:

$cat_id = get_post_meta($_REQUEST['cat']);

I think you are misunderstanding the purpose of the get_post_meta() function. It is designed to get metadata for a WordPress Post, not data from a POST request to the site. The first parameter of the get_post_meta() function is the $post_id, but since you are passing the category ID instead, you'll either get false or an array of all meta values if a post with the same ID as that category ID exists. In either of those cases, the value of the cat query var will not be a valid categroy ID, and so that part of the query will be ignored and all posts will be returned. If you change that line to this, it will fix that problem and your code will probably work:

$cat_id = absint( $_REQUEST['cat'] );

The absint() function just converts the user-supplied value into a positive integer.

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.