I want to paginate my WordPress posts in a custom loop with Ajax, so when I click on load more button posts will appear.
My code:
<?php
$postsPerPage = 3;
$args = array(
'post_type' => 'post',
'posts_per_page' => $postsPerPage,
'cat' => 1
);
$loop = new WP_Query($args);
while ($loop->have_posts()) : $loop->the_post();
?>
<h1><?php the_title(); ?></h1>
<p>
<?php the_content(); ?>
</p>
<?php
endwhile;
echo 'Load More';
wp_reset_postdata();
?>
This code does not paginate. Is there a better way to do this?
The Load More button needs to send a ajax request to the server and the returned data can be added to the existent content using jQuery or plain javascript. Assuming your using jQuery this would starter code.
Custom Ajax Handler (Client-side)
Load More
Change to:
<a id="more_posts" href="#">Load More</a>
Javascript: - Put this at the bottom of the file.
//</script type="text/javascript">
var ajaxUrl = "<?php echo admin_url('admin-ajax.php')?>";
var page = 1; // What page we are on.
var ppp = 3; // Post per page
$("#more_posts").on("click",function(){ // When btn is pressed.
$("#more_posts").attr("disabled",true); // Disable the button, temp.
$.post(ajaxUrl, {
action:"more_post_ajax",
offset: (page * ppp) + 1,
ppp: ppp
}).success(function(posts){
page++;
$(".name_of_posts_class").append(posts); // CHANGE THIS!
$("#more_posts").attr("disabled",false);
});
});
//</script>
Custom Ajax Handler (Server-side)
PHP - Put this in the functions.php file.
function more_post_ajax(){
$offset = $_POST["offset"];
$ppp = $_POST["ppp"];
header("Content-Type: text/html");
$args = array(
'post_type' => 'post',
'posts_per_page' => $ppp,
'cat' => 1,
'offset' => $offset,
);
$loop = new WP_Query($args);
while ($loop->have_posts()) { $loop->the_post();
the_content();
}
exit;
}
add_action('wp_ajax_nopriv_more_post_ajax', 'more_post_ajax');
add_action('wp_ajax_more_post_ajax', 'more_post_ajax');
Related
I used this code to my category.php and I want it to convert for my page template, this code is fully functional and working on category.php.
<?php
if (in_category('interior')) {
$cat = get_query_var('cat');
$this_category = get_category($cat);
$this_category = wp_list_categories('hide_empty=0&hierarchical=false&order=ASC&orderby=title&show_count=0&title_li=&use_desc_for_title=1&child_of='.$this_category->cat_ID."&echo=0");
if($this_category !='<li>No categories</li>') {
echo '<ul class="ul-menu">'.$this_category.'</ul>';
}
}
?>
Image Attached Sample
Use this code into your page template.
$args = array (
'cat' => array(2,6,9,13),//use category id
'posts_per_page' => -1, //showposts is deprecated
'orderby' => 'date' //You can specify more filters to get the data
);
$cat_posts = new WP_query($args);
if ($cat_posts->have_posts()) : while ($cat_posts->have_posts()) : $cat_posts->the_post();
get_template_part( 'content', 'page' );
endwhile; endif;
I think its work for you. check and let me know
I'm very new to the Wordpress. I'm currently using the FoundationPress theme and I'm trying to add a button that the user can click to load more post.
What I want is that initially the user will see four blog posts and when the user click on the read more button it will load the next four until there are no more posts and the button disappear.
I got up to the point where I can load the first four posts, but I'm having a hard time setting up a button to display the next four posts.
This is what I have so far:
<section class="row blogArticleWrapper">
<?php while ( have_posts() ) : the_post(); ?>
<?php
the_post();
$blog_posts = get_posts( array(
'post_type' => 'blog',
'posts_per_page' => 4,
'offset' => 1,
'orderby' => 'date',
'order' => 'DESC'
) );
if ( $blog_posts ):
?>
<?php
foreach ( $blog_posts as $post ):
setup_postdata($post);
?>
<article class="blog-profile small-12 columns">
<span class="name"><?php the_field("news_title"); ?></span>
<p class="writtenBy">Written by: <?php the_field("news_written_by"); ?> <span class="date">Date: <?php the_field("news_date"); ?></span></p>
</article><!-- /.profile -->
<?php endforeach;
?>
<?php endif; ?>
<?php endwhile; // end of the loop. ?>
</section><!-- /.row -->
I tried following this guide, but I don't know how to use it on my page.
Any help is appreciated,
Thanks.
Remove:
while ( have_posts() ) : the_post(); ?>
the_post();
and
<?php endwhile; // end of the loop. ?>
Change request to
$paged = get_query_var('paged') ? get_query_var('paged') : 1;
$blog_posts = get_posts( array(
'post_type' => 'blog',
'posts_per_page' => 4,
'offset' => 1,
'paged' => $paged,
'orderby' => 'date',
'order' => 'DESC'
) );
Add to functions.php
function wp_corenavi() {
global $wp_query;
$pages = '';
$max = $wp_query->max_num_pages;
if (!$current = get_query_var('paged')) $current = 1;
$a['base'] = str_replace(999999999, '%#%', get_pagenum_link(999999999));
$a['total'] = $max;
$a['current'] = $current;
$total = 1;
$a['mid_size'] = 3;
$a['end_size'] = 1;
$a['prev_text'] = '«';
$a['next_text'] = '»';
if ($max > 1) echo '<div id="pagination" class="navigation column medium-12">';
if ($total == 1 && $max > 1) $pages = '<span class="pages">' . __('Page', 'Site') . $current . ' ' . __('of', 'Site') . ' ' . $max . '</span>'."\r\n";
echo $pages . paginate_links($a);
if ($max > 1) echo '</div>';
}
Add after endforeach; - wp_corenavi();wp_reset_postdata();;
Then jQuery ajax:
//Trigger ajax at the end of page
$(window).scroll(function(){
var top = $('body,html').scrollTop();
var height = $(window).height();
var docheight = $(document).height();
var screen = Number(docheight) - Number(height);
if( top >= screen ){
$('#pagination .next').click();
}
});
//do ajax on pagination
$('#pagination .next').on('click',function(e){
e.preventDefault();
$('#pagination').remove();
$.ajax({
type: "GET",
url: $(this).attr('href'),
dataType: "html",
success: function(out){
//We get blocks from next page , change selector to yours
result = $(out).find('.short-articles-wrapper-main .short-article');
//find next page pagination,change selector to yours
pagination = $(out).find('.short-articles-wrapper-main #pagination');
//append blocks from next page to current ,change selector to yours
$('.short-articles-wrapper-main').append(result);
//append pagination from next page to current, change selector to yours
$('.short-articles-wrapper-main').append(pagination.fadeIn(200));
}
});
});
Hope it will help you.
I tried to load more posts using ajax. I see there is lot of plugins and solutions in online and stackoverflow. But none of work for me. Actually I want to do this without plugin. So I can use this in different page archive or different page template where I need this code.
Here is my code that I got from another question in stackoverflow. My score is lower, so I can't comment out there.
Here is my index.php code:
<?php get_header(); ?>
<div class="ajax-posts">
<?php
$postsPerPage = 3;
$args = array(
'post_type' => 'post',
'posts_per_page' => $postsPerPage,
);
$loop = new WP_Query($args);
while ($loop->have_posts()) : $loop->the_post();
?>
<h2><?php the_title(); ?></h2>
<?php
endwhile;
echo '<a id="more_posts" href="#">Load More</a>';
wp_reset_postdata();
?>
</div>
<script type="text/javascript">
var ajaxUrl = "<?php echo admin_url('admin-ajax.php')?>";
var page = 1;.
var ppp = 3;
$("#more_posts").on("click",function(){
$("#more_posts").attr("disabled",true);
$.post(ajaxUrl, {
action:"more_post_ajax",
offset: (page * ppp) + 1,
ppp: ppp
}).success(function(posts){
page++;
$(".ajax-posts").append(posts); // CHANGE THIS!
$("#more_posts").attr("disabled",false);
});
});
</script>
<?php get_footer(); ?>
Here is functions.php code
<?php
function more_post_ajax(){
$offset = $_POST["offset"];
$ppp = $_POST["ppp"];
header("Content-Type: text/html");
$args = array(
'post_type' => 'post',
'posts_per_page' => $ppp,
'offset' => $offset,
);
$loop = new WP_Query($args);
while ($loop->have_posts()) { $loop->the_post();
the_title();
}
exit;
}
add_action('wp_ajax_nopriv_more_post_ajax', 'more_post_ajax');
add_action('wp_ajax_more_post_ajax', 'more_post_ajax');
?>
I don't know why posts not load or not work load more link. I hope someone will be help.
Ref: https://stackoverflow.com/a/31588401/5545813
The better way is to return an array with ur post title. Then display them after the success. If the array length < ppp (there is no more post).
$array_return = array();
$loop = new WP_Query($args);
while ($loop->have_posts()) { $loop->the_post();
$content = "<h1>" . get_the_title() . "</h1>";
$content .= "<div>" . get_the_content() . "</div>";
$content .= "<div>" . get_field("your_field") . "</div>";
$array_return[] = $content;
}
echo json_encode( $array_return );
die();
In your js script,
var posts = JSON.parse(posts);
for( var i = 0; i < posts.length; i++ )
$(".ajax-posts").append(posts[i]);
if( posts.length < ur_ppp )
$("#more_posts").fadeOut();
Something like that
I've developed custom theme from scratch with _S starter theme. I'm having issue getting Wordpress next posts via ajax request on click on read more button. I've tried many articles specifically the following articles, but no luck.
Reference Links:
Load More Posts Ajax Button in Wordpress
Load Next WordPress Posts With AJAX
Load Old WordPress Posts on the Same Page with AJAX
I've tried going with above custom loops and adding custom functions with jquery script but it don't work somehow.
Here is loop code example below:
Loop in index.php
<?php query_posts('showposts=5'); if (have_posts()) : while (have_posts()) : the_post(); ?>
<article class="post-item">
<h2><?php the_title(); ?></h2>
<?php the_excerpt(); ?>
</article>
<?php endwhile; ?>
<?php else : ?>
<h2>Sorry no posts are created yet.</h2>
<p>Please create some posts to see it in action.</p>
<?php endif; wp_reset_query(); ?>
<button class="load-more-btn">Load More</button>
I'm messing with this issue for over 4-5 days, so any one can help me out with this issue with working solution will be highly appreciable.
Thanks in advance.
I maybe have a solution for your.
First be sure to have a script enqueue in your theme
wp_enqueue_script('your_js_hanlde', get_template_directory_uri() . '/js/your_js_hanlde.js', array('jquery'), '1.0.0', true );
then localize add a function to add a js var in your dom
wp_localize_script('your_js_hanlde', 'ajaxurl', admin_url( 'admin-ajax.php' ) );
In your js, add an event on 'click' on your 'Load More' button
Pass an action name and the count of article you have in your dom, the response add the content before your button 'load more'
$("#load_more").click(function()
{
$.post(ajaxurl,
{
'action': 'your_load_more',
'count': $("article.post-item").length
},
function(response)
{
var posts = JSON.parse(response);
for( var i = 0; i < posts.length; i++ )
{
if( posts[i] == "0" )
$("#load_more").fadeOut();
else
$("#load_more").before(posts[i]);
}
});
});
create a function in your functions.php
function your_load_more()
{
$count = $_POST["count"];
$cpt = 1;
$args = array(
'posts_per_page' => -1,
'post_type' => 'post', // change the post type if you use a custom post type
'post_status' => 'publish',
);
$articles = new WP_Query( $args );
$ar_posts = array();
if( $articles->have_posts() )
{
while( $articles->have_posts() )
{
$articles->the_post();
$one_post = "";
if( $cpt > $count && $cpt < $count+6 )
{
$one_post .= "<article id='" . get_the_id() . "' class='post-item'>";
$one_post .= "<h3>" . get_the_title() . "</h3>";
$one_post .= "</article>";
$ar_posts[] = $one_post;
if( $cpt == $articles->found_posts )
$ar_posts[] = "0";
}
$cpt++;
}
}
echo json_encode($ar_posts);
die();
}
add_action( 'wp_ajax_your_load_more', 'your_load_more' );
add_action( 'wp_ajax_nopriv_your_load_more', 'your_load_more' );
It work for me.
I hope that help you.
So I have select element with 3 options: men, women, unisex. Whenever a user selects a new option, the posts should reload. I now have this as ajax function:
$(document).ready(function () {
$('#select-gender').change(function(){
$.ajax({
url: ajaxurl + "/woocommerce/archive-content.php",
type: "post",
data: {option: $(this).find("option:selected").val()},
success: function(data){
//adds the echoed response to our container
$("#topdog").html(data);
}
});
});
});
And this is the archive-content.php file:
<?php
function details($opt) {
echo 'option: ' . $opt;
}
details($_POST['option']);
$selected = $_POST['option'];
// The Query
$the_query = new WP_Query( $args );
$args=array(
'gender' => $selected,
'post_type' => 'product',
'post_status' => 'publish',
'posts_per_page' => -1
);
$my_query = null;
$my_query = new WP_Query($args);
if( $my_query->have_posts() ) {
echo 'List of manly product';
while ($my_query->have_posts()) : $my_query->the_post(); ?>
<p><?php the_title(); ?></p>
<?php
endwhile;
}
wp_reset_query(); // Restore global post data stomped by the_post().
?>
I realise now that just changing the $selected variable does not reload my posts. Should I load my posts in the 'data' part of the ajax function? How would I do that?
Thanks!