0

I am trying to load more posts from custom query loop in WordPress, I have created custom post type "Businesses" and want to load "More Businesses" on click of load more button. I am using Visual Composer shortcode to add the content of Businesses. I have successfully created load more button to get more businesses but it's appending data inside mentioned "id" and also outside that id. I am not able to detect the issue.

Here is my code: In functions.php I have added this localized script::

wp_localize_script( 'test-script', 'ajax_posts', array(
    'ajaxurl' => admin_url( 'admin-ajax.php' ),
    'noposts' => __('No older posts found', 'test'),
    'page' => get_query_var( 'paged' ) ? get_query_var('paged') : 1,     
));

my main.js file code contains ajax call as follows::

function load_posts(data, button, wrapper, max_page, load_more_txt ="View All"){
       $.ajax({
            type: "POST",
            dataType: "html",
            url: ajax_posts.ajaxurl,
            data: data,
            beforeSend : function ( xhr ) {
                button.text('Loading...');
            },
            success: function(data){
                if( data ) {
                    button.text( load_more_txt ).prev().before(data);
                    ajax_posts.page++;
                wrapper.append(data);
                    if ( ajax_posts.page == max_page ) {
                        button.remove();
                    }
                }
            },
            error : function(jqXHR, textStatus, errorThrown) {
             $loader.html(jqXHR + " :: " + textStatus + " :: " + errorThrown);
            }
       });
       return false;
    }

I have called this function on document.ready ::

   $("#more_posts").on("click",function(){
        var el = $("#more_posts");
        // Disable the button.
       el.attr("disabled",true);

       var business_category = el.data('business_category');
       var business_location = el.data('business_location');
       var business_industry = el.data('business_industry');
       var post_count = el.data('post_count');
       var offset = el.data('offset');
       var max_page = el.data('max_page');

       //shortcode enable/disable options value
       var show_business_review = el.data('show_business_review');
       var show_features = el.data('show_features');
       var show_buy_giftcard = el.data('show_buy_giftcard');
       var show_book_online_button = el.data('show_book_online_button');
       var enable_coupon_discount = el.data('enable_coupon_discount');
       var show_get_free_cleaning_btn = el.data('show_get_free_cleaning_btn');

       data = {
        'business_category': business_category,
        'business_location': business_location,
        'business_industry': business_industry,
        'post_count': post_count,
        'offset': offset,
        'page': ajax_posts.page,
        'show_business_review': show_business_review,
        'show_features': show_features,
        'show_buy_giftcard': show_buy_giftcard,
        'show_book_online_button': show_book_online_button,
        'enable_coupon_discount': enable_coupon_discount,
        'show_get_free_cleaning_btn': show_get_free_cleaning_btn,
        'action': 'more_post_ajax'
    }
    var wrapper = $("#marketplace-businesses");
    var loadMoreTxt = "View All";
    // call load more posts function
       load_posts(data, el, wrapper, max_page, loadMoreTxt);
    });

After this I have added function to get ajax data and load new posts::

function more_post_ajax(){
    header("Content-Type: text/html");
    $business_category = (isset($_POST['business_category'])) ? $_POST['business_category'] : '';
   $business_location = (isset($_POST['business_location'])) ? $_POST['business_location'] : '';
   $business_industry = (isset($_POST['business_industry'])) ? $_POST['business_industry'] : '';
   $post_count = (isset($_POST['post_count'])) ? $_POST['post_count'] : 2;
   $page = (isset($_POST['page'])) ? $_POST['page'] + 1 : 1;
   $offset = (isset($_POST['offset'])) ? $_POST['offset'] : '';
   // shortcode enable disable options
   $show_business_review = (isset($_POST['show_business_review'])) ? $_POST['show_business_review'] : true;
   $show_features = (isset($_POST['show_features'])) ? $_POST['show_features'] : true;
   $show_buy_giftcard = (isset($_POST['show_buy_giftcard'])) ? $_POST['show_buy_giftcard'] : true;
   $show_book_online_button = (isset($_POST['show_book_online_button'])) ? $_POST['show_book_online_button'] : true;
   $enable_coupon_discount = (isset($_POST['enable_coupon_discount'])) ? $_POST['enable_coupon_discount'] : true;
   $show_get_free_cleaning_btn = (isset($_POST['show_get_free_cleaning_btn'])) ? $_POST['show_get_free_cleaning_btn'] : true;

   if($business_category != "") {
      $args = array(
         'tax_query' => array(
            'relation' => 'AND',
            array('taxonomy' => 'business_location', 'field'    => 'slug', 'terms'    => array($business_location)),
            array('taxonomy' => 'business_industry', 'field'    => 'slug', 'terms'    => array($business_industry)),
            array('taxonomy' => 'business_category', 'field'    => 'slug', 'terms'    => $business_category)),
      );
   } else {
      $args = array(
         'tax_query' => array(
            'relation' => 'AND',
            array('taxonomy' => 'business_location', 'field'    => 'slug', 'terms'    => array($business_location)),
            array('taxonomy' => 'business_industry', 'field'    => 'slug', 'terms'    => array($business_industry)),
         ),
      );
   }
   $args['post_type'] = 'business';
   $args['posts_per_page'] = $post_count;
   $args['post_status'] = 'publish';
    $updated_offset = (($page - 1) * $post_count);
    $args['offset'] = $updated_offset;
   $loop = new WP_Query($args);
   $out = '';
   if ($loop -> have_posts()) :
    while ($loop -> have_posts()) : $loop->the_post(); $post_id = get_the_ID();
            $out .= '<div class="businesses-wrap-content mb-10">';
            $out .= '<div class="d-flex">';
            $out .= '<div class="content-wrap pr-15"><div class="business-title"><h5 class="text-dark mb-2">'.get_the_title().'</h5>';
         $out .= '</div></div>'; //  content-wrap pr-15 closed
            $out .= '</div>'; // d-flex closed
            $out .= '</div>';
    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');

Now it gives output as::

--appended data
<div id="marketplace-businesses">
--appended data
</div>

On click of load more button, it shows output two times, one is outside the wrapper div and another one as the last child of wrapper div.

How can I show load more data only as the last child of wrapper div? What I have done wrong here?

0

1 Answer 1

1

I have used button.text( load_more_txt ).prev().before(data); and it will duplicate data for me. Now I just used button.text( load_more_txt ); to display button text after loading. Check this function now.

function load_posts(data, button, wrapper, max_page, load_more_txt ="View All"){
       $.ajax({
            type: "POST",
            dataType: "html",
            url: ajax_posts.ajaxurl,
            data: data,
            beforeSend : function ( xhr ) {
                button.text('Loading...');
            },
            success: function(data){
                if( data ) {
                    //button.text( load_more_txt ).prev().before(data);
                    button.text( load_more_txt );
                    ajax_posts.page++;
                wrapper.append(data);
                    if ( ajax_posts.page == max_page ) {
                        button.remove();
                    }
                }
            },
            error : function(jqXHR, textStatus, errorThrown) {
             $loader.html(jqXHR + " :: " + textStatus + " :: " + errorThrown);
            }
       });
       return false;
    }

This resolves my problem.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.