wp posts ajax load more - php

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

Related

Wordpress: Add Infinite Scrolling Pagination

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.

Wordpress Load More Posts onclick with ajax request jquery

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.

How to implement pagination on a custom WP_Query Ajax

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');

AJAX $.get() Not Returning any Response

I'm trying to integrate ajax for the first time in my wordpress theme I am doing. This is my first attempt and I researched on the syntax and how it works. So far, my script is executed properly but there's no response.
The $.get Request
$(document).ready(function(){
$.get('Ajax-nao.php',{cat:12,ponum:5,panum:1},function(data) {
alert('data sent'+ data);
});
});
The Ajax-nao.php
$categoryid = $_GET['cat'];
$postnum = $_GET['ponum'];
$pagenum = $_GET['panum'];
$args = array (
'cat' => $categoryid,
'posts_per_page' => $postnum,
'paged' => $pagenum
);
$q = new WP_Query($args);
while( $q->have_posts()) : $q->the_post();
$post_excerpt = get_the_excerpt();
$wrapper = '<h2 class="column-titles">' . get_the_title() . '</h2>' . '<p>' . $post_excerpt . '</p>';
echo $wrapper;
endwhile;
home.php <-- Where the results will be displayed.
<div id="social-bar">
<div id="other-posts" class="just-float-left">
<div id="other-Posts-container">
</div>
</div>
</div>
Can anyone help me pin-point my error?
WP_Query($args) returns empty set.
At the end of your PHP script change it from:
echo $wrapper;
endwhile
to:
echo $wrapper;
exit();
endwhile
echo "No results found!";
you will gain assurance if there is any data found.

Wordpress & JQuery: integrating WP function in a external php file & Redirecting urls to theme area

I have a external php file that queries the WP database for posts. I use the WP_Query class to customize my queries. It runs fine if I'm within the template files, but it won't when I add a new php file.
I would like to include the functions that WP uses to my file.
Ajax-nao.php
$categoryid = $_GET['cat'];
$postnum = $_GET['ponum'];
$pagenum = $_GET['panum'];
$args = array (
'cat' => $categoryid,
'posts_per_page' => $postnum,
'paged' => $pagenum
);
$q = new WP_Query($args);
while( $q->have_posts()) : $q->the_post();
$post_excerpt = get_the_excerpt();
$wrapper = '<h2 class="column-titles">' . get_the_title() . '</h2>' . '<p>' . $post_excerpt . '</p>';
echo $wrapper;
exit();
endwhile;
echo "No results found!";
When I run it I get this error
Fatal error: Class 'WP_Query' not found in I:\xampp\htdocs\dmp\wp-content\themes\dmp-v3\Ajax-nao.php on line 11
Also, is there a way to for $.get() to load the my php in my theme folder and not in the root directory?
Thanks.
From some research, try adding this to the top of your PHP file and change PATHHERE to the actual path:
// Include WordPress
define('WP_USE_THEMES', false);
require_once('PATHHERE/wp-blog-header.php');
For reference:
I want to run wp_query on a separate php file for an ajax call
wordpress loop with jquery .load()
There's a couple of ways to do this. One is to simply create a template file without any header or footer:
<?php
/**
* Template Name: AJAX NAO
*/
$categoryid = $_GET['cat'];
$postnum = $_GET['ponum'];
$pagenum = $_GET['panum'];
$args = array (
'cat' => $categoryid,
'posts_per_page' => $postnum,
'paged' => $pagenum
);
$q = new WP_Query($args);
while( $q->have_posts()) : $q->the_post();
$post_excerpt = get_the_excerpt();
$wrapper = '<h2 class="column-titles">' . get_the_title() . '</h2>' . '<p>' . $post_excerpt . '</p>';
echo $wrapper;
exit();
endwhile;
echo "No results found!";
Then you can use that template for a new page in your WP admin. In your jQuery, call the full URL of that page.
The harder but preferred way is to create a plugin. You'd need something like:
<?php
/*
Plugin Name: My AJAX NAO
Description: Returns NAO
Version: 1.0
Author: You
Author URI: http://yoursite.com
*/
//
function nao_callback() {
$categoryid = $_POST['cat'];
$postnum = $_POST['ponum'];
$pagenum = $_POST['panum'];
$args = array (
'cat' => $categoryid,
'posts_per_page' => $postnum,
'paged' => $pagenum
);
$q = new WP_Query($args);
while( $q->have_posts()) : $q->the_post();
$post_excerpt = get_the_excerpt();
$wrapper = '<h2 class="column-titles">' . get_the_title() . '</h2>' . '<p>' . $post_excerpt . '</p>';
echo $wrapper;
exit();
endwhile;
echo "No results found!";
}
add_action('wp_ajax_nao', 'nao_callback');
add_action('wp_ajax_nopriv_nao', 'nao_callback');
And then in your jquery:
jQuery.ajax({
url: '/wp-admin/admin-ajax.php',
method: 'POST',
dataType: 'html',
data: {
action: 'nao',
cat: '1',
ponum: '2',
panum: '3'
},
success: function(data) {
$('.js-element').html(data);
}
});
Assuming js-element is the class name of the container you want to add the result to.

Categories