Skip to Content
PHPCODE
Ajax load more in WordPress
wordpress code / September 24, 2022

how to add load more button in word press without plugin

Step by Step :

Step 1:

<?php
/**
* The Template Name: News Page
*/
get_header();
$pid = get_the_ID();
$pagetitle = get_the_title($pid);
$wcats = get_terms( array('taxonomy' => 'categories', 'hide_empty' => false,'parent' => 0) );
$background_image=get_field('background_image');
$background_image_size=$background_image['sizes']['news_background_image'];
$default_image=get_field('default_image','option');
$default_image_size=$default_image['sizes']['news_background_image'];
if(!empty($background_image_size)):
$imgPath = $background_image_size;
elseif(!empty($default_image_size)):
$imgPath = $default_image_size;
endif;
?>
<section class="hero-section hero--inner-banner windowHeight" data-aos>
<span class="gradient blue-gradient"></span>
<span class="pattern-dots right"></span>
<span class="stroke brush-stroke3"></span>
<div class="banner-image">
<img class="cover-image" src="<?php echo $imgPath;?>" alt="">
</div>
<div class="container">
<div class="content animated-el">
<h1 class="title title-sm"><?php the_title();?></h1>
</div>
</div>
<span class="dots dots-left left-bottom-80"></span>
<span class="dots dots-right right-bottom-100"></span>
</section>
<section class="section section--news-listing" data-aos>
<div class="filter">
<div class="container">
<div class="search-box">
<div class="form-group">
<input type="search" placeholder="Search" class="search-id">
<button type="submit" class="btn-icon search-btn"></button>
</div>
</div>
<div class="filter-options">
<?php 
if(!empty($wcats)) { ?>
<div class="form-group">
<select class="selectpicker" id="type1">
<option value="">Category</option>
<?php 
foreach ($wcats as $key => $value) { 
$sub_categories = get_category_children($value->term_id); 
$child_arg = array( 'hide_empty' => false, 'parent' => $value->term_id );
$sub_categories = get_terms( 'news-type', $child_arg ); 
echo '<option class="js-filter-item" value="'.$value->term_id.'">'.$value->name.'</option> ';
} 
?>
</select>
</div>
<?php } ?>
<div class="form-group">
<select class="selectpicker" id="sorting">
<option value="">Sort By</option>
<option value="ASC">Oldest First</option>
<option value="DESC">Newest First</option>
<option value="title">Alphabetically</option>
</select>
</div>
</div>
</div>
</div>
<div class="post-listing">
<div class="container">
<?php 
$posts_per_page = 6;
$query = new WP_Query( array('posts_per_page'=> $posts_per_page,'post_type' => 'c_news', 'post_status' => 'publish' , 'order' => 'DESC') );
$totalpost = $query->found_posts; 
if($query->have_posts()) { ?>
<div id="html_loader"></div>
<div id="show_post_news">
<div class="row" id="appenddata" >
<?php 
while($query->have_posts())
{
$query->the_post();
$params['post_id'] = get_the_ID();
echo template_return_get_template_part( 'template-parts/content', 'news-list',$params); ?>
<?php } ?> 
</div>
</div>
</div>
<?php }
if($totalpost > $posts_per_page){ ?>
<div class="loadmore-block load-more">
<div id="loader"></div>
<a href="javascript:void(0);" class="btn load-more-news">LOAD MORE</a> 
</div> 
<?php } ?>
<input type="hidden" name="total_post" id="total_post" value="<?php echo $query->found_posts; ?>"> 
<input type="hidden" id="offset" name="offset" value="<?php echo $posts_per_page; ?>">
</div>
</section>
<?php get_footer();

step :2 Add code functions.php

// ===================================
// Get Template part for ajax 
// ===================================
function template_return_get_template_part($slug = null, $name = null, array $params = array()) {
$slug=str_replace("//","/",$slug);
global $wp_query;
do_action("get_template_part_{$slug}", $slug, $name);
$templates = array();
if (isset($name))
$templates[] = "{$slug}-{$name}.php";
$templates[] = "{$slug}.php";
$_template_file = locate_template($templates, false, false);
if (is_array($wp_query->query_vars)) {
extract($wp_query->query_vars, EXTR_SKIP);
}
extract($params, EXTR_SKIP);
if(!empty($_template_file)){
ob_start();
include($_template_file);
$var=ob_get_contents();
ob_end_clean();
return $var;
}
}

Step 3: created file content-news-list.php

$post_id = $params['post_id'];
$post_title = get_the_title($post_id);
$content = get_the_content($post_id);
?>
<div class="col-sm-4 post-item item_list_news">
<div class="post-inner"> 
<div class="post-image bg-cover">
<?php if(has_post_thumbnail()) :
{
$theimage = wp_get_attachment_image_src( get_post_thumbnail_id ( $post->ID ),'full');
}
?>
<?php echo '<a href="'.get_permalink($post->ID).'">'; ?>
<img class="cover-image" src="<?php echo $theimage[0]; ?>" alt=""/>
</a>
<?php endif; ?>
</div>
<div class="post-content">
<span class="date"><?php echo get_the_date(); ?></span>
<h4 class="title"><?php echo '<a href="'.get_permalink().'">';?><?php the_title(); ?></a></h4>
<p><?php $content = get_the_content();$trimmed_content = wp_trim_words( $content, 15); ?><?php echo $trimmed_content; ?></p>
</div>
<?php echo '<a href="'.get_permalink($post->ID).'" class="block-link"></a>';?>
</div>
</div>

Step 4: created js file

/**-------------------News Load More Start -------------**/
function news_post_show($html1) {
var str = 'action=get_news_more_posts';
var offset = jQuery('#offset').val();
if (offset != '' && offset != 0) {
str += '&offset=' + offset;
}
var type1 = jQuery("#type1 option:selected").val();
if (type1 != '') {
str += '&type1=' + type1;
}
var sorting = jQuery("#sorting option:selected").val();
if (sorting != '') {
str += '&sorting=' + sorting;
}
var search = jQuery(".search-id").val();
if (search != '') {
str += '&search=' + search;
}
jQuery.ajax({
url: admin_ajax_url.admin_URL,
type: "POST",
dataType: "JSON",
data: str,
beforeSend: function () {
if ($html1 == 'html') {
jQuery('#appenddata').hide();
jQuery('#html_loader').addClass('html_loader');
jQuery('.load-more-news').hide();
} else {
jQuery('#loader').addClass('loader');
}
},
success: function (data) {
jQuery('#html_loader').removeClass('html_loader');
jQuery('#loader').removeClass('loader');
jQuery('.load-more-news').show();
jQuery('#appenddata').show();
jQuery('.not-found-title').hide();
var responseData = JSON.parse(JSON.stringify(data));
if (responseData.result == '') {
jQuery('#appenddata').html('<h4 class="not-found-title"> Not found any news.</h4>');
} else {
if ($html1 == 'html') {
jQuery('#appenddata').html(responseData.result);
} else {
jQuery('#appenddata').append(responseData.result);
}
}
jQuery('#offset').val(responseData.offset);
var total_post = jQuery('#show_post_news').find('.item_list_news').length;
console.log(responseData.total_post + '<=' + total_post);
if (responseData.total_post <= total_post) {
jQuery('.load-more').hide();
} else {
jQuery('.load-more').show();
}
}, error: function () {
alert('ajax error');
}
});
}
/*events post load more ajax*/

Step 5: add code this file general_function.php

// ===================================
// set the news more posts ajax function
// ===================================
add_action('wp_ajax_get_gallery_more_posts' , 'get_gallery_more_posts');
add_action('wp_ajax_nopriv_get_gallery_more_posts','get_gallery_more_posts');
function get_gallery_more_posts(){ 
$total_count = 0;
$ppp=20;
$args = array(
'post_status' => 'publish',
'post_type' => 'gallery',
'posts_per_page' => $ppp,
'order' => 'DESC',

);
if(isset($_POST['offset']) && !empty($_POST['offset'])) {
$args['offset'] = $_POST['offset'];
}
if(isset($_POST['sorting']) && !empty($_POST['sorting']) && $_POST['sorting'] == 'title' ) {
$args['order'] = 'ASC';
$args['orderby'] = $_POST['sorting'];
} else {
$args['order'] = $_POST['sorting'];
}
if(isset($_POST['types']) && !empty($_POST['types'])) {
$args['tax_query'] = array(array(
'taxonomy' => 'gallerycategories',
'field' => 'term_id',
'terms' => $_POST['types']
));
}
$result = array();
$Media_query = new WP_Query($args);
$result['result'] = '';
if( $Media_query->have_posts() ) 
{ 
while ($Media_query->have_posts()) 
{
$Media_query->the_post();
$params['post_id'] = get_the_ID();
$result['result'] .= franciscanuniversity_return_get_template_part( 'template-parts/content', 'gallery-list',$params);
} 
}
wp_reset_postdata(); 
$result['offset'] = $ppp + $_POST['offset'];
$result['total_post'] = $Media_query->found_posts;
$result['query'] = $Media_query->request;
echo json_encode($result);
exit;
}
// ===================================
// set the news more posts ajax function
// ===================================

 

 

PHPCODE © 2024