I'm using "Users Following System" plugin. So far I added a list of the following/followers into the author.php profile, now I'm trying to use Ajax with this but the problem I'm facing that I need to get the same user meta for each user by ID, So that everyone can see the following users of each other.
In author.php I used this line to get the users information.
<?php
$curauth = (isset($_GET['author_name'])) ? get_user_by('slug', $author_name) : get_userdata(intval($author));
?>
And this line to get the user meta of _pwuf_following
$include = get_user_meta($curauth->ID, '_pwuf_following', true);
But when I added the same lines within the Ajax function handler not working.
i tried get_queried_object(); wp_get_current_user(); get_userdata();
but I always failing.
Here's the snippet from author.php to get the list of following users.
<?php
$curauth = (isset($_GET['author_name'])) ? get_user_by('slug', $author_name) : get_userdata(intval($author));
$include = get_user_meta($curauth->ID, '_pwuf_following', true);
if ( empty( $include ) ) {
echo 'Not followed anyone yet.';
} else {
$args = array (
'order' => 'DESC',
'include' => $include,
'number' => 52,
'paged' => 1
);
$wp_user_query = new WP_User_Query( $args );
$users = $wp_user_query->get_results();
echo '<div id="top-artists-contributors-3">';
echo '<ul id="grid-contributors-4">';
echo '<li class="scroll-artists">';
foreach ( $users as $user ) {
$avatar_size = 90;
$avatar = get_avatar($user->user_email, 200);
$author_profile_url = get_author_posts_url($user->ID);
$profile = get_userdata($user->ID);
echo '<div class="single-item-3">';
echo '<div class="author-gravatar-3">', $avatar , '</div>';
echo '<div class="members-name">' . $profile->first_name .'</div>';
echo '</div>';
}
echo '</li>';
echo '</ul>';
echo '</div>';
}
?>
This is the js to get Ajax url and action
<script type="text/javascript">
var ajaxurl = "<?php echo admin_url( 'admin-ajax.php' ); ?>";
var page = 2;
var canBeLoaded = true,
bottomOffset = 2000;
jQuery(function($) {
$(window).scroll(function() {
if( $(document).scrollTop() > ( $(document).height() - bottomOffset ) && canBeLoaded == true ) {
canBeLoaded = false;
var data = {
'action': 'user_following_by_ajax',
'page': page,
'security': '<?php echo wp_create_nonce("user_more_following"); ?>'
};
$.post(ajaxurl, data, function(response) {
$('#following').append(response);
canBeLoaded = true;
page++;
});
}
});
});
</script>
And this is from the function.php of Ajax handler.
add_action('wp_ajax_user_following_by_ajax', 'user_following_by_ajax_callback');
add_action('wp_ajax_nopriv_user_following_by_ajax', 'user_following_by_ajax_callback');
function user_following_by_ajax_callback() {
check_ajax_referer('user_more_following', 'security');
$paged = $_POST['page'];
$curauth = (isset($_GET['author_name'])) ? get_user_by('slug', $author_name) : get_userdata(intval($author));
$include = get_user_meta($curauth->ID, '_pwuf_following', true);
if ( empty( $include ) ) {
echo 'Not followed anyone yet.';
} else {
$args = array (
'order' => 'DESC',
'include' => $include,
'number' => 52,
'paged' => $paged
);
$wp_user_query = new WP_User_Query( $args );
$users = $wp_user_query->get_results();
echo '<div id="top-artists-contributors-3">';
echo '<ul id="grid-contributors-4">';
echo '<li class="scroll-artists">';
foreach ( $users as $user ) {
$avatar_size = 90;
$avatar = get_avatar($user->user_email, 200);
$author_profile_url = get_author_posts_url($user->ID);
$profile = get_userdata($user->ID);
echo '<div class="single-item-3">';
echo '<div class="author-gravatar-3">', $avatar , '</div>';
echo '<div class="members-name">' . $profile->first_name .'</div>';
echo '</div>';
}
echo '</li>';
echo '</ul>';
echo '</div>';
}
wp_die();
}
I can see you don't pass the author_name field which is used in your code. Please check below code where I have added the missing field.
<script type="text/javascript">
var ajaxurl = "<?php echo admin_url( 'admin-ajax.php' ); ?>";
var page = 2;
var canBeLoaded = true,
bottomOffset = 2000;
jQuery(function($) {
$(window).scroll(function() {
if( $(document).scrollTop() > ( $(document).height() - bottomOffset ) && canBeLoaded == true ) {
canBeLoaded = false;
var data = {
'action': 'user_following_by_ajax',
'data': { page : 'page', author_name: '<?php echo get_the_author(); ?>' }, // Here set author name which you are getting.
'security': '<?php echo wp_create_nonce("user_more_following"); ?>'
};
$.post(ajaxurl, data, function(response) {
$('#following').append(response);
canBeLoaded = true;
page++;
});
}
});
});
</script>
Related
I have a question related with Wordpress Ajax posts request. And I can't figure out for hours... Maybe someone will give me advice what I'm doing wrong!
Problem:
So I have infinite scroll on my archive pages. Everything is working as it should but for some reason it loads all the time the same 20 posts... What I need to change to have infinite scroll as long as created posts exists.
Here is my JS code:
function loadArticle() {
var loading = false;
$(window).bind('scroll', function() {
var page = $(this).data('page');
var newPage = page + 1;
var maxPages = $("#content").data('max-pages');
var postType = false;
var search = getQueryVariable("s");
if ( $('body').hasClass('post-type-archive-news') ) {
postType = 'news';
} else if ( $('body').hasClass('post-type-archive-ebooks') ) {
postType = 'ebooks';
} else if ( $('body').hasClass('post-type-archive-lookbooks') ) {
postType = 'lookbooks';
} else if ( $('body').hasClass('post-type-archive-case-studies') ) {
postType = 'case-studies';
} else if ( $('body').hasClass('post-type-archive-events') ) {
postType = 'events';
} else if ( $('body').hasClass('search-results') ) {
postType = false;
} else {
postType = 'post';
}
var query = 'action=infinite_scroll';
if ( newPage ) {
query = query + '&page_no=' + newPage;
}
if ( typeof postType == "string" ) {
query = query + "&post_type=" + postType;
}
if ( typeof search == "string" ) {
query = query + "&search=" + search;
}
// Show Loader
//$('a#inifiniteLoader').show('fast');
// Load Next Page
if(!loading && $(window).scrollTop() >= ($('#content').offset().top + $('#content').outerHeight() - window.innerHeight)) {
loading = true;
$.ajax({
url: "/wp-admin/admin-ajax.php",
type:'POST',
data: query,
success: function(html){
$("#content").append(html); // This will be the div where our content will be loaded
loading = false;
}
});
}
return false;
});
}
And this is my PHP
function yieldify_infinite_scroll(){
//init ajax
$ajax = false;
//check ajax call or not
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) &&
strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$ajax = true;
}
$paged = $_POST['page_no'] + 1;
$post_type = $_POST['post_type'];
$search = $_POST['s'];
$args = array(
'posts_per_page' => get_option('posts_per_page'),
'paged' => $paged,
'orderby' => 'date',
'order' => 'DESC',
'post_status' => 'publish'
);
if ( $post_type ) {
$args['post_type'] = $post_type;
}
if ( $search ) {
$args['s'] = $post_type;
}
// Load the posts
//query_posts( $args );
$ajax_query = new WP_query( $args );
//echo "<pre>";
//$print_query = json_encode( $ajax_query, JSON_PRETTY_PRINT );
//$print_query = htmlentities( $print_query, ENT_QUOTES, 'utf-8' );
//print_r( $print_query );
//echo "</pre>";
if( $ajax_query->have_posts() ) {
while( $ajax_query->have_posts() ) { $ajax_query->the_post();
if ( $post_type ) { ?>
<div class='col-12 col-md-6 col-lg-4 d-flex'>
<?php get_template_part('loops/card-new'); ?>
</div><!-- .col -->
<?php } else {
echo "<div class='col-12'>";
get_template_part('loops/search-results');
echo "</div>";
}
}
}
wp_reset_postdata();
//check ajax call
if($ajax) die();
exit;
}
add_action('wp_ajax_infinite_scroll', 'yieldify_infinite_scroll'); // for logged in user
add_action('wp_ajax_nopriv_infinite_scroll', 'yieldify_infinite_scroll');
My archive layout looks like that:
<?php if( have_posts() ) : $paged = (get_query_var('paged')) ? get_query_var('paged') : 1; ?>
<section id="blog-listing" class="resources-section">
<div class='container'>
<div class='row' id="content">
<?php while( have_posts() ) : the_post(); ?>
<div class='col-12 col-md-6 col-lg-4 d-flex'>
<?php get_template_part('loops/card-new'); ?>
</div><!-- .col -->
<?php endwhile; ?>
</div><!-- .row -->
<div class='row'>
<div class='col-12 text-center'>
Show More
</div><!-- .col -->
</div><!-- .row -->
</div><!-- .container -->
</section><!-- #blog-listing -->
<?php endif; ?>
I would be appreciated for any help!
It seems to me that you need to update the value in $(this).data('page')
You get it, do an increment on the variable, but you do not store it back. Try to modify as follow.
var page = $(this).data('page');
var newPage = page + 1;
$(this).data('page', newPage);
Here is My code, it should be filtering by category, it displays all posts on any checkbox I click, I don't know how to fix this, I have tried everything.
<form id="filter">
<?php
if( $terms = get_terms( 'category', 'orderby=name' ) ) : // to make it simple I use default categories
foreach ( $terms as $term ) :
echo '<input type="checkbox" name="category[]" value="' . $term->term_id . '" class="br">' . $term->name;
echo '';
endforeach;
endif;
?>
<div class="filter-output"></div>
</form>
Here is the js (coded inside a template page)
jQuery('#filter .br').click(function(){
// Declaratie van array
var choices = {};
jQuery('.contents').remove();
jQuery('.filter-output').empty();
jQuery('input[type=checkbox]:checked').each(function() {
if (!choices.hasOwnProperty(this.name))
choices[this.name] = [this.value];
else
choices[this.name].push(this.value);
});
console.log(choices);
jQuery.ajax({
url: '<?php echo admin_url('admin-ajax.php'); ?>',
type :'POST',
data : {
'action' : 'call_post', // Naam van de PHP functie
'choices' : choices,
},
success: function (result) {
jQuery('.filter-output').append(result);
// Voor testen - Resultaat (Kan later verwijderd worden)
//console.log(Resultaat);
//console.log(Keuzes);
},
error: function(err){
// Voor testen - Error (Kan later verwijderd worden)
console.log(err);
console.log(choices);
}
});
})
funstions.php
add_action('wp_ajax_call_post', 'call_post');
add_action('wp_ajax_nopriv_call_post', 'call_post');
function call_post(){
// Verkijgen van AJAX data:
$choices = $_POST['choices'];
$meta_query = array('relation' => 'OR');
foreach($choices as $Key=>$Value){
if(count($Value)){
foreach ($Value as $Inkey => $Invalue) {
$meta_query[] = array( 'key' => $Key, 'value' => $Invalue, 'compare' => '=' );
}
}
}
$args = array(
'post_type' => 'post',
'meta_query' =>$meta_query
);
$query = new WP_Query($args);
//if( ! empty ($params['template'])) {
////$template = $params['template'];
if( $query->have_posts() ) :
while( $query->have_posts() ): $query->the_post();
the_title();
endwhile;
wp_reset_query();
else :
wp_send_json($query->posts);
endif;
//}
die(); }
Anyone please help, I have been trying to make this work since yesterday and with no luck at all
I've refactored your code and made it work:
Template:
<?php
/**
*
* Template Name: Filter Posts
*
*/
get_header();
$args = array(
'post_type' => 'post',
'posts_per_page' => -1,
);
$tax_query = array();
$categories = get_terms( 'category', 'orderby=name' );
if ( ! empty( $choices = get_request_param( 'choices' ) ) ) {
$term_ids = explode(',', $choices);
$tax_query[] = array(
'taxonomy' => 'category',
'field' => 'term_id',
'terms' => $term_ids
);
$args['tax_query'] = $tax_query;
}
$query = new WP_Query( $args );
if ( ! empty( $categories ) ) : ?>
<form action="?" method="post" class="form-filter">
<?php foreach ( $categories as $category ) : ?>
<div class="checkbox">
<input type="checkbox" name="category[]" data-category="<?php echo esc_attr( $category->term_id ); ?>" id="<?php echo esc_attr( $category->slug ); ?>">
<label for="<?php echo esc_attr( $category->slug ); ?>">
<?php echo esc_html( $category->name ); ?>
</label>
</div><!-- /.checkbox -->
<?php endforeach; ?>
</form><!-- /.form-filter -->
<?php endif; ?>
<div class="filter-output">
<ul>
<?php while ( $query->have_posts() ) : $query->the_post(); ?>
<li>
<?php the_title(); ?>
</li>
<?php endwhile; ?>
</ul>
</div><!-- /.filter-output -->
<?php
wp_reset_postdata();
get_footer();
Javascript:
;(function(window, document, $) {
var $win = $(window);
var $doc = $(document);
$doc.on('change', '.form-filter', function() {
var choices = '';
$('.form-filter input:checked').each(function() {
if ( choices === '' ) {
choices += $(this).data('category');
} else {
choices += ',' + $(this).data('category');
}
});
$.ajax({
url: window.location.href,
type: 'GET',
data: {
'choices' : choices,
},
success: function(response) {
var newPosts = $(response).filter('.filter-output').html();
$('.filter-output').html(newPosts);
}
});
});
})(window, document, window.jQuery);
functions.php
function get_request_param( $key = '' ) {
$value = false;
if ( ! $key ) {
return $value;
}
if ( isset( $_POST[$key] ) ) {
$value = $_POST[$key];
} elseif ( isset( $_GET[$key] ) ) {
$value = $_GET[$key];
}
return $value;
}
Few notes:
1) Use jquery change event, instead of click for the filter form.
2) WP AJAX is not needed in this case. You can simply make a GET request to the same page and change the HTML where needed.
3) Use GET method instead of POST
I will try to be clear this time, I'm using "Users Following System" plugin. And I added a list of the following/followers users into the author.php profile, now I'm trying to use Ajax pagination.
For sure into author.php I used this line to get the users information.
<?php
$curauth = (isset($_GET['author_name'])) ? get_user_by('slug', $author_name) : get_userdata(intval($author));
?>
And this line to get the user meta of _pwuf_following
$include = get_user_meta($curauth->ID, '_pwuf_following', true);
This is what i did in author.php to get the list of following users.
<?php
$curauth = (isset($_GET['author_name'])) ? get_user_by('slug', $author_name) : get_userdata(intval($author));
$include = get_user_meta($curauth->ID, '_pwuf_following', true);
if ( empty( $include ) ) {
echo 'Not followed anyone yet.';
} else {
$args = array (
'order' => 'DESC',
'include' => $include,
'number' => 52,
'paged' => 1
);
$wp_user_query = new WP_User_Query( $args );
$users = $wp_user_query->get_results();
echo '<div id="top-artists-contributors-3">';
echo '<ul id="grid-contributors-4">';
echo '<li class="scroll-artists">';
foreach ( $users as $user ) {
$avatar_size = 90;
$avatar = get_avatar($user->user_email, 200);
$author_profile_url = get_author_posts_url($user->ID);
$profile = get_userdata($user->ID);
echo '<div class="single-item-3">';
echo '<div class="author-gravatar-3">', $avatar , '</div>';
echo '<div class="members-name">' . $profile->first_name .'</div>';
echo '</div>';
}
echo '</li>';
echo '</ul>';
echo '</div>';
}
?>
And this is the JS to get Ajax action also in author.php
<script type="text/javascript">
var ajaxurl = "<?php echo admin_url( 'admin-ajax.php' ); ?>";
var page = 2;
var canBeLoaded = true,
bottomOffset = 2000;
jQuery(function($) {
$(window).scroll(function() {
if( $(document).scrollTop() > ( $(document).height() - bottomOffset ) && canBeLoaded == true ) {
canBeLoaded = false;
var data = {
'action': 'user_following_by_ajax',
'page': page,
'security': '<?php echo wp_create_nonce("user_more_following"); ?>'
};
$.post(ajaxurl, data, function(response) {
$('#following').append(response);
canBeLoaded = true;
page++;
});
}
});
});
</script>
And this is from function.php of the Ajax handler.
add_action('wp_ajax_user_following_by_ajax', 'user_following_by_ajax_callback');
add_action('wp_ajax_nopriv_user_following_by_ajax', 'user_following_by_ajax_callback');
function user_following_by_ajax_callback() {
check_ajax_referer('user_more_following', 'security');
$paged = $_POST['page'];
$curauth = (isset($_GET['author_name'])) ? get_user_by('slug', $author_name) : get_userdata(intval($author));
$include = get_user_meta($curauth->ID, '_pwuf_following', true);
if ( empty( $include ) ) {
echo 'Not followed anyone yet.';
} else {
$args = array (
'order' => 'DESC',
'include' => $include,
'number' => 52,
'paged' => $paged
);
$wp_user_query = new WP_User_Query( $args );
$users = $wp_user_query->get_results();
echo '<div id="top-artists-contributors-3">';
echo '<ul id="grid-contributors-4">';
echo '<li class="scroll-artists">';
foreach ( $users as $user ) {
$avatar_size = 90;
$avatar = get_avatar($user->user_email, 200);
$author_profile_url = get_author_posts_url($user->ID);
$profile = get_userdata($user->ID);
echo '<div class="single-item-3">';
echo '<div class="author-gravatar-3">', $avatar , '</div>';
echo '<div class="members-name">' . $profile->first_name .'</div>';
echo '</div>';
}
echo '</li>';
echo '</ul>';
echo '</div>';
}
wp_die();
}
No errors but not working, I get "Not followed anyone yet." instead of the following users, what i did wrong, Thanks.
I have a strange and frustrating behaviour of wordpress admin-ajax.php file, when i make an ajax request it returns 400 error bad request.
var ajaxurl = '<?php echo site_url() ?>/wp-admin/admin-ajax.php';
var true_posts = '<?php echo serialize($wp_query->query_vars); ?>';
var current_page = <?php echo (get_query_var('paged')) ? get_query_var('paged') : 1; ?>;
var max_pages = '<?php echo $wp_query->max_num_pages; ?>';
jQuery(function($){
$('#true_loadmore').click(function(){
$(this).text('Loading...');
var data = {
'action': 'loadmore',
'query': true_posts,
'page' : current_page
};
$.ajax({
url:ajaxurl,
data:data,
type:'POST',
success:function(data){
if( data ) {
$('#true_loadmore').text('View more recent Posts').before(data);
current_page++;
if (current_page == max_pages) $("#true_loadmore").remove();
} else {
$('#true_loadmore').remove();
}
}
});
});
});
my functions.php .
add_action('wp_ajax_loadmore', 'true_load_posts');
add_action('wp_ajax_nopriv_loadmore', 'true_load_posts');
function true_load_posts(){
$args = unserialize( stripslashes( $_POST['query'] ) );
$args['paged'] = $_POST['page'] + 1;
$args['post_status'] = 'publish';
query_posts( $args );
if( have_posts() ) :
while( have_posts() ): the_post();
get_template_part( 'template-parts/post/content', get_post_format() );
endwhile;
endif;
die();
}
And I got 400 error .
Someone could help me to please? thank you.
the problem should be the action in your sending data.
The 'action' value must correspond to the function name in the php side (and in the add_action method ).
var data = {
'action': 'true_load_posts', //instead of 'loadmore'
'query': true_posts,
'page' : current_page
};
Hope this help.
I'm using the starter theme Sage to create a custom Wordpress Theme. I made a very simple infinite scroll system to display every posts. On that point, everything seems to work fine.
Now, I have to display an advertisement block each N posts in the loop. At first sight, it seemed pretty easy, but unfortunately, it was not.
My system works this way :
When the blog page is displayed, the firsts N posts are shown. In that template (Template 1), in the loop, I call a method to check if I have to display an advertisement.
When the user starts to scroll, the next N posts are loaded with AJAX. So, JS calls a Wordpress action which loads the next posts and call the appropriate template (Template 2). In that template, I check again how many posts have passed and if I have to display an advertisement.
Counting informations are stocked in session variables.
The problem is this one :
When the page is loaded, everything is fine. When the infinite scroll operates for the first time, it still fine. But, when the system is called once again, the counting informations stocked in variables session are not good. They take the previous values like if the session variables were not incremented.
At first time, I used some static attributes and a static method but it didn't work. So, I thought it was because the script was not call at once and I used global variables. But it didn't work either.
It seems that the counting works fine but every time the template called by AJAX is loaded, the session variables are reset to their previous values, like if they were late.
Here are the files that I use :
Template 1, it's the index.php of the theme
Template 2, the file called by AJAX
Ajax functions, which contains all the AJAX actions I need in Wordpress
Advertisement Controller, which contains every method relative to the advertisements blocks
A JS file with the different AJAX queries.
Can somebody tell what I am doing wrong? It will be much appreciated.
Please, find my code below:
Template 1
/****************************************/
/********** TEMPLATE 1 - INDEX **********/
/****************************************/
use Roots\Sage\ThemeAdvertisementController;
$AdvertisementController = new ThemeAdvertisementController\AdvertisementController();
$_SESSION['globalCountAds'] = 0;
$_SESSION['globalArrayAds'] = '';
$_SESSION['globalCountPosts'] = 1;
get_template_part('templates/page', 'header');
while (have_posts()) {
the_post();
get_template_part('templates/content', get_post_type() != 'post' ? get_post_type() : get_post_format());
$theLoopAd = $AdvertisementController->getTheLoopAds();
if ( $theLoopAd ) {
echo $theLoopAd;
}
}
Template 2
/**************************************************/
/********** TEMPLATE 2 - CALLDED BY AJAX **********/
/**************************************************/
use Roots\Sage\ThemeAdvertisementController;
$AdvertisementController = new ThemeAdvertisementController\AdvertisementController();
while (have_posts()) {
the_post();
get_template_part( 'templates/content', get_post_type() != 'post' ? get_post_type() : get_post_format() );
$theLoopAd = $AdvertisementController->getTheLoopAds();
if ( $theLoopAd ) {
echo $theLoopAd;
}
}
Advertisement Controller
/**********************************************/
/********** ADVERTISEMENT CONTROLLER **********/
/**********************************************/
namespace Roots\Sage\ThemeAdvertisementController;
use Roots\Sage\ThemeViewController;
use Roots\Sage\ThemePostController;
class AdvertisementController {
public function __construct() {
}
private function getTheAds() {
$PostController = new ThemePostController\PostController();
$postType = 'advertisement';
$nbPosts = -1;
$status = 'publish';
$orderBy = 'title';
$order = 'ASC';
$meta = '';
$taxQuery = '';
$metaQuery = array(
array(
'key' => 'advertisement_in_news',
'value' => true,
'compare' => '='
)
);
return $PostController->getThePosts( $postType, $nbPosts, $status, $orderBy, $order, $meta, $taxQuery, $metaQuery );
}
private function displayTheAd() {
$ViewController = new ThemeViewController\ViewController();
$theAdsArray = $_SESSION['globalArrayAds'];
$theGlobalCountAds = $_SESSION['globalCountAds'];
$thePostID = $theAdsArray->posts[ $theGlobalCountAds ]->ID;
if ( !empty( $thePostID ) ) {
$_SESSION['globalCountAds']++;
$ViewController->postID = $thePostID;
$ViewController->postType = 'advertisement';
$ViewController->nbPosts = 1;
$ViewController->status = 'publish';
$ViewController->orderBy = 'ID';
$ViewController->order = 'ASC';
$ViewController->meta = '';
$ViewController->taxQuery = '';
return $ViewController->displayAdvertisementBlock();
} else {
return false;
}
}
public function getTheLoopAds() {
$arrayAds = $_SESSION['globalArrayAds'];
$adsCount = $_SESSION['globalCountAds'];
$postCount = $_SESSION['globalCountPosts'];
$_SESSION['globalCountPosts']++;
if ( empty( $arrayAds ) ) {
$theAds = $this->getTheAds();
$_SESSION['globalArrayAds'] = $theAds;
}
if ( $postCount%2 == 0 && $postCount != 0 ) {
$displayedAd = $this->displayTheAd();
if ( $displayedAd ) {
return $displayedAd;
} else {
return false;
}
} else {
return false;
}
}
}
Ajax functions
/************************************/
/********** AJAX FUNCTIONS **********/
/************************************/
function infinitePaginateAjax() {
$paged = $_POST['paged'];
$postsPerPage = get_option('posts_per_page');
$args = array( 'paged' => $paged,
'post_status' => 'publish',
'order' => 'DESC',
'post_type' => 'post',
'posts_per_page' => $postsPerPage
);
query_posts( $args );
get_template_part('templates/loop-news');
exit;
}
add_action( 'wp_ajax_infinitePaginateAjax','infinitePaginateAjax' );
add_action( 'wp_ajax_nopriv_infinitePaginateAjax','infinitePaginateAjax' );
function getNbPostsPerPageAjax() {
$value = array();
$nbPostsPerPage = get_option('posts_per_page');
if ( !empty( $nbPostsPerPage ) ) {
$value['answer'] = 1;
$value['value'] = $nbPostsPerPage;
$value['globalCountAds'] = $_SESSION['globalCountAds'];
$value['globalCountPosts'] = $_SESSION['globalCountPosts'];
} else {
$value['answer'] = 0;
$value['value'] = 0;
}
$data = json_encode( $value );
die( $data );
}
add_action( 'wp_ajax_getNbPostsPerPageAjax','getNbPostsPerPageAjax' );
add_action( 'wp_ajax_nopriv_getNbPostsPerPageAjax','getNbPostsPerPageAjax' );
function getTotalPostsAjax() {
global $wp_query;
$value = array();
$nbPosts = wp_count_posts( 'post' );
$nbPublishedPosts = $nbPosts->publish;
if ( !empty( $nbPublishedPosts ) ) {
$value['answer'] = 1;
$value['value'] = $nbPublishedPosts;
$value['globalCountAds'] = $_SESSION['globalCountAds'];
$value['globalCountPosts'] = $_SESSION['globalCountPosts'];
} else {
$value['answer'] = 0;
$value['value'] = 0;
}
$data = json_encode( $value );
die( $data );
}
add_action( 'wp_ajax_getTotalPostsAjax','getTotalPostsAjax' );
add_action( 'wp_ajax_nopriv_getTotalPostsAjax','getTotalPostsAjax' );
JS
jQuery(document).ready(function() {
var pageInfinite = '.infinite-page';
var loaderInfinite = '.infinite-loader';
var contentInfinite = '.main-content';
var getTotalPosts = function() {
var totalPosts = '';
jQuery.ajax({
type : "POST",
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
async: false,
url : data_sage_js.ajaxurl,
data: {
action: 'getTotalPostsAjax'
},
success: function( data ) {
data = jQuery.parseJSON( data );
if ( data.answer !== 0 ) {
totalPosts = data.value;
} else {
totalPosts = 0;
}
},
error: function () {
console.log( 'error: cannot get nb posts' );
totalPosts = 0;
}
});
return totalPosts;
};
var getNbPostsPerPage = function() {
var postsPerPage = '';
jQuery.ajax({
type : "POST",
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
async: false,
url : data_sage_js.ajaxurl,
data: {
action: 'getNbPostsPerPageAjax'
},
success: function( data ) {
data = jQuery.parseJSON( data );
if ( data.answer !== 0 ) {
postsPerPage = data.value;
} else {
postsPerPage = 0;
}
},
error: function () {
console.log( 'error: cannot get max posts page' );
postsPerPage = 0;
}
});
return postsPerPage;
};
var infiniteLoadArticle = function( pageNumber ) {
jQuery( loaderInfinite ).show( 'fast' );
setTimeout(function(){
jQuery.ajax({
type:'POST',
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
async: false,
url: data_sage_js.ajaxurl,
data: {
action: 'infinitePaginateAjax',
paged: pageNumber
},
success: function( html ) {
jQuery( loaderInfinite ).hide( 'fast' );
jQuery( contentInfinite ).append( html);
}
});
}, 1000);
return false;
};
if ( jQuery( pageInfinite ).length > 0 ) {
var postsTotal = parseInt( getTotalPosts() );
var incPost = parseInt( getNbPostsPerPage() );
var postsCount = parseInt( incPost );
var nbPage = parseInt( 1 );
var nbTotalPage = parseInt( Math.ceil( postsTotal / incPost ) );
jQuery(window).scroll(function() {
if ( jQuery(window).scrollTop() === jQuery(document).height() - jQuery(window).height() ) {
if ( nbTotalPage > nbPage ) {
nbPage++;
infiniteLoadArticle( nbPage );
postsCount = postsCount + incPost;
} else if ( nbTotalPage <= nbPage ) {
return false;
}
}
});
}
});
EDIT/SOLVE
So, after hours of searching, I decided to do it another way : I decided to use the "posts_per_page" attribute to count posts and to know when I have to display an advertisement. I just had to refactor a few functions and methods.
Do session variables work outside of the Ajax Calls? on page refresh etc.
If they do not then it may be to do with the fact that wordpress can treat session variables very weirdly.
I think its for security but if in your php.ini if 'register_globals' is on it unregisters all of the php globals.
Reference: WP_unregister_GLOBALS
In which case I believe things like https://wordpress.org/plugins/wp-session-manager/ fill in the blanks for this, or you could turn off register_globals in your php.ini (although I dont understand the repercussions of doing that sorry