Ajax error in Wordpress load more? - ajax

I have try to load option for my custom page template, Ajax return undefined error After click load more button.
Custom blog page
<?php if (have_posts()) : ?>
<section id="posts">
<?$postslist = get_posts( array(
'posts_per_page' => 2,
'order' => 'ASC'
) );
if ( $postslist ) {
foreach ( $postslist as $post ) :
setup_postdata( $post );
?>
<div style='color:#000'>
<?php echo '<br>'.$post->ID.'->'; the_title(); ?>
</div>
<?php
endforeach;
wp_reset_postdata();
} ?>
</section>
<?php if ( $wp_query->max_num_pages > 1 ) : ?>
<nav class="load_more">
<?php next_posts_link( 'Load More' ); ?>
</nav>
<?php endif; ?>
<?php endif; ?>
<div class="load_more"><a>list</a></div>
Custom js
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>');
$.get(link, function(data) {
var post = $("#posts .post ", data);
$('#posts').append(post);
});
jQuery('.load_more').load(link+' .load_more a');
});
Ajax Error:
GET http://kannan.test.dev/blog/
200 OK
398ms
jquery....=1.11.1 (line 4)
GET http://kannan.test.dev/blog/undefined
404 Not Found
321ms
jquery....=1.11.1 (line 4)
"NetworkError: 404 Not Found - http://kannan.test.dev/blog/undefined"

You're trying to get the url by accessing the href attribute in your jQuery function, but you're not supplying it, that's why the url has undefined appended at the end.
You need to set your "href" attribute here
<div class="load_more"><a href='...'>list</a></div>
in order for this line of code to work:
var link = jQuery(this).attr('href');

Related

Filter AJAX search results in WordPress by page template

I am making a WordPress website, which is made up of a Woocommerce Store + Blog section. Both in the Store and on the Blog there is a search engine that shows instant results with AJAX. What I want to do is that, depending on the page where the user is (Blog page or Store page), the search engine will only show results of articles or products, respectively.
After googling and testing, I understood that the conditional tags of Wordpress (is_home (), is_shop (), etc) don't work if they are called from the functions.php file, and the AJAX php function I'm using is effectively inside the functions.php.
The AJAX php function is as follows:
<?php
/**
* Adding ajax search functionality to the theme
*/
add_action('wp_ajax_nopriv_ajax_search','ajax_search');
add_action('wp_ajax_ajax_search','ajax_search');
function ajax_search(){
global $post;
$args = array(
'post_type' => 'post',
'post_status' => 'publish',
's' =>$_POST['term'],
'posts_per_page' =>10
);
$query = new WP_Query( $args );
// display results
if( $query->have_posts() ) : ?>
<?php while( $query->have_posts() ) : $query->the_post(); ?>
<li>
<?php
$terms = get_the_terms( $post->ID, 'category' );
foreach ($terms as $term) {
break;
} ?>
<a title="<?php the_title(); ?>" href="<?php the_permalink(); ?>"> <?php the_title(); ?> </a>
<div class="clear"></div>
</li>
<?php endwhile;
wp_reset_postdata(); ?>
<?php else: ?>
<li class="no-results-ajax">No results.</li>
<?php endif; ?>
<?php exit;
}
?>
The JQuery function linked with the previous function is as follows:
function buscar_ajax(input1, input2) {
input1.keyup(function(e) {
// prevent browser autocomplete
jQuery(this).attr('autocomplete','off');
// get search term
var searchTerm = jQuery(this).val();
var urlFull = window.location.href; // URL completa
var ruta = window.location.pathname; // URL sin "http://dominio.com"
var dominio = urlFull.replace(ruta,''); // URL solo "http://dominio.com"
if(searchTerm.length > 2) {
jQuery.ajax({
url: dominio + "/wp-admin/admin-ajax.php",
type:"POST",
data:{
'action':'ajax_search',
'term' :searchTerm
},
success:function(result){
input2.fadeIn(200).html(result);
}
});
} else {
input2.fadeOut(200);
}
if(searchTerm.length == 0){
input2.hide();
}
if(e.keyCode == 27){
jQuery(this).val('');
input2.hide();
}
jQuery('body').click(function(e){
if ( !jQuery(e.target).hasClass("busqueda") ) {
input2.fadeOut(200);
jQuery(this).val('');
}
});
});
input1.keypress(function(e) {
if(e.keyCode == 27){
jQuery(this).val('');
input2.fadeOut(200);
}
});
}
var buscaHead1 = jQuery('input#s');
var buscaHead2 = jQuery('ul#dhemy-ajax-search');
buscar_ajax( buscaHead1, buscaHead2 );
And the HTML code of the search form:
<form role="search" method="get" id="buscador-blog" class="searchform" action="<?php echo esc_url( home_url( '/' ) ); ?>">
<input class="busqueda" type="text" value="" name="s" id="s" placeholder="Busca en el blog..."/>
<ul id="dhemy-ajax-search"></ul> <!-- AJAX search -->
<input type="submit" id="searchsubmit" value="" />
<input type="hidden" name="search-type" value="post" />
</form>
So far, the result is that AJAX shows blog articles or products or articles and products. (changing 'post' to 'product' in the 'post_type' parameter of the $ args array). I need that, if the person is on the Store page, they only show products and if they are on the Blog page, they only show posts.
This could be done if only I had some conditional to evaluate what type of page the user is viewing, and that is where I am trapped.
I very much appreciate any help or guidance you can give me.

How to add load more button ajax button to this wordpress loop?

<main class="main aktualitasu_saraksta_konteineris" role="main">
<?php
$args = array(
'post_type' => 'post',
'posts_per_page' => -1,
'group_by' => 'date',
'order' => 'DESC',
'ignore_sticky_posts' => 1
);
$query = new WP_Query($args);
?>
<?php if ($query->have_posts()) : while ($query->have_posts()) : $query->the_post(); ?>
<?php get_template_part( 'parts/loop', 'news' ); ?>
<?php endwhile; endif; wp_reset_postdata();?>
</main>
How to add load more button that load posts with ajax?
You will need to do this in javascript rather than in php look at this https://www.w3schools.com/jquery/jquery_ajax_get_post.asp. You will need to add button in html say
<button id="load_more" type="button">Load More</button>
And then in javascript (this is an example using jQuery)
$("#load_more").click(function(){
$.get("your/route", function(data, status){
//here you can add the data to the page depending on what the data is
});
});
your/route is whatever route you have set in php for fetching more posts

i'm using the loop + jQuery below to load in the next set of pages but it's showing only 2 pages but i have 20 post and i'm showing 4 post perpage

<?php $new_query = new WP_Query();
$new_query->query('showposts=4'.'&paged='.$paged);?>
<?php while ($new_query->have_posts()) : $new_query->the_post(); ?>
<li>
<?php the_title();?>
</li>
<?php endwhile; ?>
<div id="pagination">
<?php if(function_exists('wp_pagenavi')) { wp_pagenavi(); } else { ?>
<div class="alignleft">
<?php next_posts_link('« Older Entries') ?>
</div>
<div class="alignright">
<?php previous_posts_link('Newer Entries »') ?>
</div>
<?php
} ?>
</div>
it's working but only showing 2 pages but i have 20 posts and i'm showing 4 posts per page
<script>
jQuery(function($) {
$('ul.govtjobs').on('click', '#pagination a', function(e){
e.preventDefault();
var link = $(this).attr('href');
$('ul.govtjobs').fadeOut(100, function(){
$(this).load(link + ' ul.govtjobs', function() {
$(this).fadeIn(100);
});
});
});
});
</script>
and i'm using this script for go to next page
Try this:
<?php
$args = array(
'posts_per_page' => 4,
'paged' => $paged,
);
$new_query = new WP_Query($args);
It is recommended to use posts_per_page.

Query vars in url (wordpress) work fine when page loaded directly, but fail on ajax

I've a little issue, and I couldn't find anything about it... I'm in deadlock.
So I've wp page that contains normal loop, if I call this file directly in browser all works fine, and I can even use query-vars such as: http://domain.com/blog/wp-content/themes/wovies-bones/getmovies.php?actor=x And it works fine, I get single post that has custom taxonomy actor = x.
But when I try to load same using ajax, it behaves differently and ignoring my get request returns all posts...
Any ideas what is happening?
ajax-jquery part:
$.ajax({
url: templatePath + "getmovies.php",
type: "GET",
data: filters_get,
cache: false,
success: function (data){
console.dir(data);
}
});
And php part:
/* Define these, So that WP functions work inside this file */
define('WP_USE_THEMES', false);
require('../../../wp-blog-header.php');
?>
<div id="container">
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<div class="movie">
<a href="<?php the_permalink() ?>">
<?php
if (has_post_thumbnail()) {the_post_thumbnail('homepage-preview');}
else {echo '<img src="' . get_bloginfo( 'stylesheet_directory' ) . '/images/default-poster.jpg" />';}
?>
<p class="comments"><?php comments_number('0 review','1 review','% reviews'); ?></p>
<div class="description">
<h2><?php the_title(); ?></h2>
<?php the_excerpt(); ?>
</div>
</a>
</div>
<?php endwhile; else: ?>
<!-- No movies found -->
<?php endif; ?>
</div><!-- End #container -->
filters_get looks like this: ?actor=x&
This way, you just load WordPress and run your own PHP file. Basicaly, I think you should redefine your WP_Query like this :
/*Define these, So that WP functions work inside this file */
define('WP_USE_THEMES', false);
require('../../../wp-blog-header.php');
global $wp_query;
$args = array(
'post_type' => 'my-post-type',
'my_tax' => $_GET['my_tax']
);
$wp_query = new WP_Query($args);
// Your template stuff
And if you're using AJAX to get your posts, you'd better use a hooked function as it is described in WordPress Codex :
add_action('wp_ajax_get_my_cpt', 'get_my_cpt');
add_action('wp_ajax_nopriv_get_my_cptn', 'get_my_cpt');
function get_my_cpt() {
$args = array(
'post_type' => 'my-post-type',
'my_tax' => $_GET['my_tax']
);
$cpts = get_posts($args);
if(empty($cpts)) {
_e('No custom post to show');
exit;
}
foreach($cpts as $cpt) {
// Do you stuff to display your custom posts
}
}
Then you will have to use this kind of url in your AJAX call : http://www.domain.tld/wp-admin/admin-ajax.php?action=get_my_cpt&my_tax=keyword

wordpress showing comments from a post retrieved with ajax

i'm loading a post with ajax.
The code is
$(document).ready(function(){
loadPostsFun = function(){
$.ajax({
url: "http://lab1.koalamedia.es/ajax/",
//url: "/random/",
success: function(response){
$("#randomPost").html( response );
}
});
};
$("#another").click(function(){
loadPostsFun();
return false;
});
});
The response is generated by a custom template with this code:
<?php
query_posts('showposts=1&orderby=rand');
the_post();
$args = array( 'numberposts' => 1, 'orderby' => 'date' );
$rand_posts = get_posts( $args );
?>
<?php
foreach( $rand_posts as $post ) : setup_postdata($post);
?>
<div id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<?php if ( is_front_page() ) { ?>
<h2 class="entry-title"><?php the_title(); ?></h2>
<?php } else { ?>
<h1 class="entry-title"><?php the_title(); ?></h1>
<?php } ?>
<div class="entry-content">
<?php the_content(); ?>
<?php wp_link_pages( array( 'before' => '<div class="page-link">' . __( 'Pages:', 'twentyten' ), 'after' => '</div>' ) ); ?>
<?php comments_popup_link(__('Comments (0)'), __('Comments (1)'), __('Comments (%)')); ?>
</div><!-- .entry-content -->
</div><!-- #post-## -->
<?php
//comments_template( '', true ); //this doesn't work
comment_form();
//wp_list_comments(''); //this doesn't work
?>
<?php endforeach; ?>
The ajax request works but the comments doesn't show.All the post data is there.
How can i show the comments?
neither comments_template or wp_list_comments work.
You can view a demo or download the template sample i've done here
Without much tweaking wp_list_comments() works in a comments template (usually comments.php) only.
Use get_comments(), pass the post ID as parameter:
$comments = get_comments(array ( 'post_id' => $post->ID );
if ( $comments )
{
foreach ( $comments as $comment )
{
print "<li>$comment->comment_author<br>$comment->comment_content</li>";
}
}
i've found the problem, i forgot to set the global variable:
global $withcomments;
i was using
$withcomments = true;
comments_template();
but without the global it didn't work.
Now works like normal comments do.

Resources