Link to home
Start Free TrialLog in
Avatar of Robert Granlund
Robert GranlundFlag for United States of America

asked on

Wordpress Query

I Wordpress want to run a query with AJAX but  I only want to grab/ show the 18 returns after the first 18.  So when I run the query it returns all of the posts that fix my arguments.  Lets say I have 60 posts that match my arguments but I only want to show the 19th through the 36th post.  How do I write that?  Here is what I have:
<?php
function be_ajax_load_more() {
    $args = array(
        'posts_per_page' => 18,
        'post_type' => 'post',
        'post_status' => 'publish',
        'suppress_filters' => true,
        "tax_query" => array(
            array(
                "taxonomy" => "promotion",
                "field" => "slug",
                "terms" => "curated"
            )
        ),
    );
    ob_start();
    $posts_array = get_posts($args);
    global $post;
    $count_start = isset($_POST['count_start']) ? $_POST['count_start'] : false;
    foreach ($posts_array as $post) {
        $field_name = "show_video";
        $id = $post->ID;
        $video = get_field($field_name, $id);
        $category = $category[0]->cat_name;
        $title = $post->post_title;
        $title = mb_strimwidth($title, 0, 50, '...');
        $tumbnail = get_the_post_thumbnail($id);
        $category = get_the_category();
        ?>      
// DO SOMETHING  //
        <?php
    }
    //  END Foreach

    wp_reset_postdata();
    $data = ob_get_clean();
    wp_send_json_success($data);
    wp_die();
}

Open in new window


So with my query saying 18 posts per page, I gues I want to return page 2?  How do I do that?  I'm creating a variation of the infinite loop.
ASKER CERTIFIED SOLUTION
Avatar of Julian Hansen
Julian Hansen
Flag of South Africa image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Robert Granlund

ASKER

@ julian, can I change the offset to whatever I want?  Meaning, post back to a hidden field the next offset I want to run cause the next time it runs I would want the offset to be 36
Yes - the offset is what you specify the starting to point to be - however this has the side effect of breaking pagination.

https://codex.wordpress.org/Template_Tags/get_posts
@julian:
I need to increase the number by 18 each time the AJAX it runs.  But it does not see the offset that I have created.
LINE 4 of the html grabs the offset
and passes it to line: 15  of the SCRIPT.

IN The PHP line:5 & 10  / offset does not seem to be set.

But Line:82  is updated with the correct number and is placed back on the page through the script

What am I doing wrong that the offset is not reading the number?
<?php
function be_ajax_load_more_all() {

$offset = isset($_POST['offt']) ? $_POST['offt'] : false;
$offset = intval($offset);

    $args = array(
        'nopaging' => true,
        'posts_per_page' => 18,
        'offset' => $offset,
        'post_type' => 'post',
        'post_status' => 'publish',
        'suppress_filters' => true
    );
    ob_start();
    $posts_array = get_posts($args);
    global $post;
    foreach ($posts_array as $post) {
        $field_name = "show_video";
        $id = $post->ID;
        $video = get_field($field_name, $id);
        $category = $category[0]->cat_name;
        $title = $post->post_title;
        $title = mb_strimwidth($title, 0, 50, '...');
        $tumbnail = get_the_post_thumbnail($id);
        $category = get_the_category();
        ?>      


        <div class="col-md-4 col-sm-6 col-xs-12">
            <div id="post-<?php echo $id; ?>" <?php post_class(); ?>>
                <div class="item" onclick="document.location.href = '<?php the_permalink($post->ID); ?>'; return false">

                    <div class="thumbnail">


        <?php
        if (!empty($video)) {
            echo '<div class="video-play">
                                            <img src="' . get_home_url() . '/wp-content/themes/surfline/img/playbtn.svg" alt="video" class="video-play-controller">
                                            </div>';
        }
        ?>   
                        <?php
                        $title = get_the_title();
                                        the_post_thumbnail($id, array( 'title' => $title,  'alt'   => $title )); 
                        ?>         </div>


                    <div class="meta">

        <?php
        foreach ($category as $c) {
            $cat_name = $c->cat_name;
            $cat_slug = $c->slug;
            echo '<a href="../' . $cat_slug . '">' . $cat_name . '</a>';
            break;
        }
        ?> 

                        <span><i class="fa fa-clock-o" aria-hidden="true"></i>&nbsp;<?php echo get_the_date('Y-m-d'); ?>  
        <?php
        $before = "| <strong>Updated</strong>&nbsp;";
        if (get_the_modified_time('U') != get_the_time('U')) {
            echo $before;
            echo human_time_diff(get_the_modified_date('U'), current_time('timestamp')) . ' ' . __('ago');
        }
        ?>
                        </span>

                    </div>
        <?php echo'<div class="headline">' . $title . '</div>'; ?>

                </div>
            </div>
        </div>
        <?php
    }
    //  END Foreach
$offset = $offset + 18;
    ?>
<div id="offsets" style="display:none;"><?php echo $offset; ?></div>
<?php
    wp_reset_postdata();
    $data = ob_get_clean();
    wp_send_json_success($data);
    wp_die();
}

Open in new window


<script>
jQuery(function ($) {
    $('.post-listing-all').append('<span class="load-more"></span>');
    var button = $('.post-listing-all .load-more');
    var page = 2;
    var loading = false;
    var scrollHandling = {
        allow: true,
        reallow: function () {
            scrollHandling.allow = true;
        }
    };

    $(window).scroll(function () {
        var offt = $('#offsets').html()
        if (!loading && scrollHandling.allow) {
            scrollHandling.allow = false;
            setTimeout(scrollHandling.reallow, scrollHandling);
            var offset = $(button).offset().top - $(window).scrollTop();
            if (700 > offset) {
                loading = true;
                $('#loading-image').bind('ajaxStart', function(){
    $(this).show();
}).bind('ajaxStop', function(){
    $(this).hide();
});
                var data = {
                    action: 'be_ajax_load_more_all',
                    page: page,
                    offt:offt,
                    query: beloadmore.query,
                };
                $.post(beloadmore.url, data, function (res) {
                 $( "#offsets" ).remove();
                    if (res.success) {
                        $('.post-listing-all').append(res.data);
                        $('.post-listing-all').append(button);
                        page = page + 1;
                        loading = false;
                    } else {
                        //console.log(res);
                         //console.log('hi');
                    }
                }).fail(function (xhr, textStatus, e) {
                    //console.log(xhr.responseText);
                    //console.log('fail');
                });

            }
        }
    });
    
});

Open in new window


<html>
<div id="offsets" style="display:none;">18</div>

Open in new window

I see you have accepted a solution - have you found a solution to your problem?