0

I have a working AJAX post loader, but I can't get it working on the category page. What am I doing wrong? I think I'm not getting categories correctly?

The category.php code:

<div id="ajaxCatPosts" class="cat-post-side left small-12 large-9">
    <?php 
    while ( have_posts() ) : the_post();
       include(__DIR__.'/views/cat-post-thumb.php');
    endwhile;
    ?>
    <div class="load-button">
       <button id="more_cat_posts">Veel uudiseid</button>
    </div>
</div>

The functions.php code:

function more_post_ajax(){

        $ppp = (isset($_POST["ppp"])) ? $_POST["ppp"] : 16;
        $page = (isset($_POST['pageNumber'])) ? $_POST['pageNumber'] : 0;

        header("Content-Type: text/html");

        $args = array(
            'suppress_filters' => true,
            'posts_per_page' => $ppp,
            'paged'    => $page,
        );

        $loop = new WP_Query($args);

        if ($loop -> have_posts()) :  while ($loop -> have_posts()) : $loop -> the_post();

            include(__DIR__.'/views/cat-post-thumb.php');

        endwhile;
        endif;
        wp_reset_postdata();
        die($out);
    }

    add_action('wp_ajax_nopriv_more_post_ajax', 'more_post_ajax');
    add_action('wp_ajax_more_post_ajax', 'more_post_ajax');

And here is loadmore.js:

$(function() {
    var ppp = 16; // Post per page
    var pageNumber = 1;

    function load_posts(){
        pageNumber++;
        var str = '&pageNumber=' + pageNumber + '&ppp' + ppp + '&action=more_post_ajax';
        $.ajax({
            type: "POST",
            dataType: "html",
            url: ajax_posts.ajaxurl,
            data: str,
            success: function(data){
                var $data = $(data);
                if($data.length){
                    $("#ajax-posts").append($data);

                    $("#more_posts").attr("disabled",false);
                } else{
                    $("#more_posts").attr("disabled",true);
                }
            },
            error : function(jqXHR, textStatus, errorThrown) {
                $loader.html(jqXHR + " :: " + textStatus + " :: " + errorThrown);
            }

        });
        return false;
    }

    $('#more_posts').unbind('click');

    $("#more_posts").on("click",function(){ // When btn is pressed.
        $("#more_posts").attr("disabled",true); // Disable the button, temp.
        load_posts();
    });
});
Nathaniel Ford
  • 20,545
  • 20
  • 91
  • 102
  • What 'isn't working'? You need to be specific about what you *expect* and what you're *actually* getting back. – Nathaniel Ford Feb 15 '16 at 20:32
  • i am getting all posts. But id like to have gategory posts. Like if im on the archive page milk then it loads me only posts with category milk not all. – Magnus Pääru Feb 15 '16 at 20:38

2 Answers2

0

The answer to your question seems to be in the documentation here.

Specifically, before making the call to WP_Query you need to specify the category you want. You're currently setting up the query here:

$args = array(
    'suppress_filters' => true,
    'posts_per_page' => $ppp,
    'paged'    => $page,
);

And you'll need to extend that to this:

$args = array(
    'category_name' => $category
    'suppress_filters' => true,
    'posts_per_page' => $ppp,
    'paged'    => $page,
);

This means that your AJAX call will need to include the category you want (`$category) in the JSON, or you'll have to extract it from the page url. One way you could do this is:

$args = array(
    'suppress_filters' => true,
    'posts_per_page' => $ppp,
    'paged'    => $page,
);
if (isset($_POST["category"]){
    $args['category_name'] = $_POST["category"];
}

Correspondingly, you'd need to update your AJAX call to have a category element:

var str = '&pageNumber=' + pageNumber + '&ppp' + ppp + '&action=more_post_ajax' + '&category=milk';
Nathaniel Ford
  • 20,545
  • 20
  • 91
  • 102
  • How to make this AJAX call category element dynamic? That it depends on what category page this button is? – Magnus Pääru Feb 15 '16 at 21:05
  • You will have to parse the url in javascript, probably. http://stackoverflow.com/questions/736513/how-do-i-parse-a-url-into-hostname-and-path-in-javascript – Nathaniel Ford Feb 15 '16 at 21:06
0

To make it work more dynamically with any taxonomy or combinations of taxonomies so this solutions would work not only in category.php but in any other case. For example JS could pass taxonomy term arguments where to fetch pposts from.

So first in your AJAX call we need to pass in the term where we want to load our posts from, lets say category is named milk. (And also lets make POST arguments more readable)

function load_posts(){
    pageNumber++;

    var str = {
        pageNumber: pageNumber,
        ppp: ppp,
        term: 'milk',
        action: 'more_post_ajax'
    };

    $.ajax({
        type: "POST",
        dataType: "html",
        url: ajax_posts.ajaxurl,
        data: str,
        success: function(data){
            var $data = $(data);
            if($data.length){
                $("#ajax-posts").append($data);

                $("#more_posts").attr("disabled",false);
            } else{
                $("#more_posts").attr("disabled",true);
            }
        },
        error : function(jqXHR, textStatus, errorThrown) {
            $loader.html(jqXHR + " :: " + textStatus + " :: " + errorThrown);
        }

    });
    return false;
}

In your PHP code

function more_post_ajax(){

    $ppp = (isset($_POST["ppp"])) ? $_POST["ppp"] : 16;
    $page = (isset($_POST['pageNumber'])) ? $_POST['pageNumber'] : 0;
    $term = isset($_POST['term']) ? $_POST['term'] : 0;

    header("Content-Type: text/html");

    $args = array(
        'suppress_filters' => true,
        'posts_per_page' => $ppp,
        'paged'    => $page,
        'tax_query' => array(
            array(
                'taxonomy' => 'category',
                'field'    => 'slug', // Depends whether JS passes you slug or ID of taxonomy term, in our case it is a slug
                'terms'    => array( $term ),
            )
        ),
    );

    $loop = new WP_Query($args);

    if ($loop -> have_posts()) :  while ($loop -> have_posts()) : $loop -> the_post();

        include(__DIR__.'/views/cat-post-thumb.php');

    endwhile;
    endif;
    wp_reset_postdata();
    die();
}

add_action('wp_ajax_nopriv_more_post_ajax', 'more_post_ajax');
add_action('wp_ajax_more_post_ajax', 'more_post_ajax');

Your WP_Query is now hardcoded to search from category taxonomy where posts have terms that match with the queried ones. You could change it to whatever you want, your not stuck with category taxonomy only if you change tax_query in your arguments. To be more secure you might want to check if that term exists in that taxonomy first.