PHP Developer

Thursday, 16 November 2017

WordPress Custom Load More Posts Button Without Plugin

WordPress Custom Load More Posts Without Plugin



STEP 1 : Insert this code in functions.php file

<?php
/************ Pagination Function START *************/
function wp_pagination() {
    global $wp_query;
    $big = 12345678;
    $page_format = paginate_links( array(
        'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),
        'format' => '?paged=%#%',
        'current' => max( 1, get_query_var('paged') ),
        'total' => $wp_query->max_num_pages,
        'type'  => 'array'
    ) );
    if( is_array($page_format) ) {
        $paged = ( get_query_var('paged') == 0 ) ? 1 : get_query_var('paged');
        echo '<div class="pagination"><ul>';
        echo '<li><span>'. $paged . ' of ' . $wp_query->max_num_pages .'</span></li>';
        foreach ( $page_format as $page ) {
                echo "<li>$page</li>";
        }
       echo '</ul></div>';
    }
}
/************ Pagination Function END *************/
?>

STEP 2 : Template code to get posts with Load morebutton

<?php
   $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
   query_posts(array(  
       'post_type' => 'product', //Post Type
       'post_status' => 'publish', //Post Status
       'paged' => $paged 
   ));
   ?>
<?php if (have_posts()) : ?>
    <section id="posts">
       <?php while (have_posts()) : the_post(); ?>
       <article class="post"><?php echo get_the_title();?></article><br>
       <?php endwhile; ?>
    </section>
    <?php if ( $wp_query->max_num_pages > 1 ) : ?>
        <nav class="load_more">
           <?php next_posts_link( 'Load More' ); ?>
        </nav>
        <script type="text/javascript">
            jQuery(document).ready(function(){
                jQuery('.load_more a').live('click', function(e){
                    e.preventDefault();
                    var link = jQuery(this).attr('href');
                    jQuery('.load_more').html('<span class="loader">Loading More Posts...</span>');
                    jQuery.get(link, function(data) {
                        var post = jQuery("#posts .post ", data);
                        jQuery('#posts').append(post);
                    });
                    jQuery('.load_more').load(link+' .load_more a');
                });
            });
        </script>
    <?php endif;  ?>
<?php endif;  ?>


No comments:

Post a Comment