Wordpress Load More Posts onclick with ajax request jquery - php

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.

Related

Displaying post titles in a specific category in a shortcode (wordPress)

Trying to write my first short-code that displays all post-titles in a specific Category. But it is not displaying the actual results, just the short code.
Here is what I have so far in my child theme's functions.php file:
function posts_in_cat() {
echo '<ul>';
query_posts('cat=3'); while (have_posts()) : the_post();
echo ('<li>' . the_title() . '</li>');
endwhile;
wp_reset_query();
echo '</ul>';
}
add_shortcode( 'display_posts_in_cat', 'posts_in_cat' );
And then I am calling the short code, like so [display_posts_in_cat].
Any help would be greatly appreciated as I try and learn this.
EDIT: I have gotten it to display but the link itself is being echo-ed in front of the title in text. Also, it is not displaying more than 10 of the titles and I want it to display them all. Any ideas...?? Thanks.
First and foremost, avoid using query_posts() – it's inefficient. Check out this SO answer for the skinny.
Additionally, shortcodes shouldn't make use of echo statements. Shortcodes only return text. Put simply, WordPress has PHP internally that says "when this specific shortcode is entered into the editor, replace it with the text returned from this function." Using echo causes you to immediately print those statements to the screen, rather than returning to WordPress so that it can continue with its regular process. More on the WP Codex.
And, finally, shortcode functions require $atts as a parameter.
So, with all that said, here's how I would rewrite your function:
<?php
function posts_in_cat( $atts ) {
$atts = shortcode_atts( array(
'cat' => '',
), $atts );
if ( empty( $atts['cat'] ) ) {
// If category provided, exit early
return;
}
$args = array(
'category' => $atts['cat'],
// Disable pagination
'posts_per_page' => -1
);
$posts_list = get_posts( $args );
if ( empty( $posts_list) ) {
// If no posts, exit early
return;
}
$opening_tag = '<ul>';
$closing_tag = '</ul>';
$post_content = '';
foreach ( $posts_list as $post_cat ) {
$post_content .= '<li>' . esc_html( get_the_title( $post_cat->ID ) ) . '</li>';
}
return $opening_tag . $post_content . $closing_tag;
}
add_shortcode( 'display_posts_in_cat', 'posts_in_cat' );
I'm just adding all of the content you were echoing into a handful of variables, and then returning them, concatenated, at the end. Also, I added in an if statement to exit early if there aren't any posts in the category. That way you don't have an empty <ul> element cluttering up the page.
I've also escaped the outputs, which you can read about on the Codex.
Please try this:
function posts_in_cat() { ?>
<ul class="posts">
<?php query_posts('cat=3&showposts=50'); while (have_posts()) : the_post();
?>
<li><a href='<?php the_permalink() ?>'><?php the_title(); ?></a></li>
<?php endwhile; ?>
<?php wp_reset_query(); ?>
</ul>
<?php
}
add_shortcode( 'display_posts_in_cat', 'posts_in_cat' );

Shortcode in Wordpress causes Openserver death

So I have a custom PHP page in Wordpress that displays some content:
<? while(have_posts() ) : the_post(); ?>
<?the_content();?>
<? endwhile; ?>
I need to display the list of news related with this content, so I wrote a shortcode for that:
function generate_program_news(){
$news_args = array( 'posts_per_page' => 5, 'cat' => 4);
$news_query = new WP_Query($news_args);
$news_data;
while( $news_query->have_posts() ) {
$news_date = get_permalink();
$news_title = the_title();
$news_data = "<a>" .$news_date. ": " .$news_title. "</a>";
}
wp_reset_postdata();
return $news_data;
}
add_shortcode('program_news','generate_program_news');
But when I add [program_news] shortcode and try to access the page I used it in, the entire website dies off until I have the OpenServer rebooted. What am I doing wrong?
while( $news_query->have_posts() )
you must type
$news_query->the_post();

wp posts ajax load more

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

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

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