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.
Related
I am trying to improve the speed of my infinite scroll code. Here is my ajax requet handling script
function ga_infinite_scroll() {//trigger this on infinite scroll
add_filter( 'woocommerce_get_price_html', 'ga_show_price' );//filter to fix price range
if(empty($_POST['search_term'] )){
$params = json_decode( stripslashes( $_POST['query'] ), true );
$params['post_status'] = 'publish';
$params['posts_per_page'] = get_option('posts_per_page');
$params['post_type'] = 'product';
$params['paged'] = $_POST['page'] + 1; // we need next page to be loaded
}
else{//search logic here
$search_query = json_decode( stripslashes( $_POST['search_posts'] ), true );
$search_query['post_status'] = 'publish';
$search_query['posts_per_page'] = get_option('posts_per_page');
$search_query['paged'] = $_POST['page'] + 1;
wc_set_loop_prop( 'total', $_POST['search_count'] );
$params = $search_query;
}
ob_start();
query_posts( $params);
if ( have_posts() ) {//product loop
if ( wc_get_loop_prop( 'total' ) ) {
while ( have_posts() ) {
the_post();
wc_get_template_part( 'content', 'product' );
}
}
}
$data = ob_get_clean();
die($data);
exit;
}
add_action( 'wp_ajax_ga_infinite_scroll', 'ga_infinite_scroll' );
add_action( 'wp_ajax_nopriv_ga_infinite_scroll', 'ga_infinite_scroll' );
Here is my javascript:-
jQuery(document).ready( function($) {
var url = window.location.origin + '/wp-admin/admin-ajax.php',
canBeLoaded=true,
bottomOffset = 2000; // the distance (in px) from the page bottom when you want to load more posts
$(window).scroll(function(){
var data = {
'action': 'ga_infinite_scroll',
'query': my_ajax_object.posts,
'page' : my_ajax_object.current_page,
//'search_results' : my_ajax_object.ga_search_results,
'search_count' : my_ajax_object.ga_search_count,
'search_posts': my_ajax_object.ga_search_posts,
'search_term' : my_ajax_object.ga_search_term,
'user_currency': my_ajax_object.user_currency,
'reg_price_slug': my_ajax_object.reg_price_field_slug
};
if( $(document).scrollTop() > ( $(document).height() - bottomOffset ) && canBeLoaded == true ){
$.ajax({//limit the ajax calls
url : url,
data:data,
type:'POST',
beforeSend: function( xhr ){
// you can also add your own preloader here
// you see, the AJAX call is in process, we shouldn't run it again until complete
//console.log(data.search_term);
$('#ajax-loader').show();
canBeLoaded = false;
},
success:function(data){
if( data ) {
$('#multiple-products .columns-3 .products ').find('li:last-of-type').after( data ); // where to insert posts
//console.log(url);
canBeLoaded = true; // the ajax is completed, now we can run it again
my_ajax_object.current_page++;
$('#ajax-loader').hide();
}
else{
$('#ajax-loader').html('End of products...').delay(1000).fadeOut();
return;
}
}
});
}
});
//setting if it's a search
});
I'm wondering if it's a good idea to use query_posts and I have this filter that costly in terms of speed but if I don't use it, I end up seeing a price range like this $15-$25 like that.Any idea about how to handle this situation and to see the code of ga_show_price and my enqueued script, I've added it here Improving the speed of a custom infinite scroll and also any suggestions on improving my javascript?Thanks
You can get related products using the following:
$array = wc_get_related_products( $product_id, $limit, $exclude_ids );
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>
I have an AJAX "show more posts" script running on my WordPress page.
The only thing is when I click "show more" and reach the end, I would like for the button to change and say "show less" then close all of the AJAX that was shown.
How could I alter my current script to do that?
Below is the code
<div id="work" class="case-studies">
<h2>
Case studies
</h2>
<div class="case-study-squares">
<div id="ajax-posts" class="row">
<?php
$args = array(
'post_type' => 'casestudies',
'post_status' => 'publish',
);
$casestudies = new WP_Query( $args );
if( $casestudies->have_posts() ) :
?>
<?php
$postsPerPage = 4;
$args = array(
'post_type' => 'casestudies',
'posts_per_page' => $postsPerPage,
'cat' => 0
);
$loop = new WP_Query($args);
while ($loop->have_posts()) : $loop->the_post();
?>
<div class="case-open-container">
<div class="case-toggle"><?php the_post_thumbnail('large'); ?><h3><?php echo
the_title(); ?></h3></div>
</div>
<?php
endwhile;
wp_reset_postdata();
?>
</div>
<?php
else :
esc_html_e( 'No case studies posted yet!', 'text-domain' );
endif;
?>
</div>
</div>
<div id="more_posts" class="view-more">
<h3>
View more work
</h3><p class="down-arrow">
▼
</p>
</div>
Below code is from my functions file
wp_enqueue_script( 'custom_js', get_template_directory_uri(). '/js/custom.js', array( 'jquery'), '', true ); wp_localize_script( 'custom_js', 'ajax_posts', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ), 'noposts' => __('No older posts found', 'enzyme-communications'), ));
function more_post_ajax(){
$ppp = (isset($_POST["ppp"])) ? $_POST["ppp"] : 4;
$page = (isset($_POST['pageNumber'])) ? $_POST['pageNumber'] : 0;
header("Content-Type: text/html");
$args = array(
'suppress_filters' => true,
'post_type' => 'casestudies',
'posts_per_page' => $ppp,
'cat' => 0,
'paged' => $page,
);
$loop = new WP_Query($args);
$rows = get_field('repeater_field_name');
if($rows)
{ $image = get_sub_field('image'); }
$out = '';
if ($loop -> have_posts()) : while ($loop -> have_posts()) : $loop -> .
the_post();
$out .= ' <div class="case-more-container">
<div class="case-more-toggle"><img src="'.get_the_post_thumbnail_url().'"> .
<h3>'.get_the_title().'</h3></div>
</div>
';
endwhile;
endif;
wp_reset_postdata();
die($out);
}
add_action('wp_ajax_nopriv_more_post_ajax', 'more_post_ajax');
add_action('wp_ajax_more_post_ajax', 'more_post_ajax');
Below is the custom.js that also relates to this
$(document).ready(function(){
var ppp = 4; // Post per page
var cat = 0;
var pageNumber = 1;
function load_posts(){
pageNumber++;
var str = '&cat=' + cat + '&pageNumber=' + pageNumber + '&ppp=' + ppp +
'&action=more_post_ajax';
$.ajax({
type: "POST",
dataType: "html",
url: ajax_posts.ajaxurl,
data: str,
success: function(data){
var $data = $(data);
if($data.length){
$("#ajax-posts").append($data);
$("#more_posts").attr("disabled",false);
} else{
$("#more_posts").attr("disabled",true);
}
},
error : function(jqXHR, textStatus, errorThrown) {
$loader.html(jqXHR + " :: " + textStatus + " :: " + errorThrown);
}
});
return false;
}
$("#more_posts").on("click",function(){ // When btn is pressed.
$("#more_posts").attr("disabled",true); // Disable the button, temp.
load_posts();
});
});
Really appreciate any help given in advance :)
I hope this would help you!
Try this out
$(document).ready(function(){
var ppp = 4; // Post per page
var cat = 0;
var pageNumber = 1;
$("#more_posts").text("Show More");
function load_posts(){
pageNumber++;
var str = '&cat=' + cat + '&pageNumber=' + pageNumber + '&ppp=' + ppp +
'&action=more_post_ajax';
$.ajax({
type: "POST",
dataType: "html",
url: ajax_posts.ajaxurl,
data: str,
success: function(data){
var $data = $(data);
if($data.length){
$("#ajax-posts").append("<div id='ajax-posts-'" + pageNumber + ">" + $data + "</div>");
$("#more_posts").text("Show More");
$("#more_posts").attr("disabled",false);
} else{
//If there are no more posts
$("#more_posts").text("Show Less");
$("#more_posts").attr("disabled",true);
}
},
error : function(jqXHR, textStatus, errorThrown) {
$loader.html(jqXHR + " :: " + textStatus + " :: " + errorThrown);
}
});
return false;
}
function less_posts(){
$("#ajax-posts-" + pageNumber).remove();
pageNumber--;
}
$("#more_posts").on("click",function(){ // When btn is pressed.
$("#more_posts").attr("disabled",true); // Disable the button, temp.
if($("#more_posts").text == "Show More")
{
load_posts();
}
else if($("#more_posts").text == "Show Less")
{
less_posts();
}
});
});
Thank you ;)
I don't know, How your code works , but my script helps to change the text.
check this and try with your code, hope this will help you.
jQuery(document).ready(function(){
jQuery("#more_posts").on("click",function(){ // When btn is pressed.
jQuery(this).toggleClass("less_show");
if(jQuery(this).hasClass("less_show")){
jQuery("#more_posts h3").text('View less work ');
}
else{
jQuery("#more_posts h3").text('View more work ');
}
});
});
I have a working AJAX post loader, but I can't get it working on the category page. What am I doing wrong? I think I'm not getting categories correctly?
The category.php code:
<div id="ajaxCatPosts" class="cat-post-side left small-12 large-9">
<?php
while ( have_posts() ) : the_post();
include(__DIR__.'/views/cat-post-thumb.php');
endwhile;
?>
<div class="load-button">
<button id="more_cat_posts">Veel uudiseid</button>
</div>
</div>
The functions.php code:
function more_post_ajax(){
$ppp = (isset($_POST["ppp"])) ? $_POST["ppp"] : 16;
$page = (isset($_POST['pageNumber'])) ? $_POST['pageNumber'] : 0;
header("Content-Type: text/html");
$args = array(
'suppress_filters' => true,
'posts_per_page' => $ppp,
'paged' => $page,
);
$loop = new WP_Query($args);
if ($loop -> have_posts()) : while ($loop -> have_posts()) : $loop -> the_post();
include(__DIR__.'/views/cat-post-thumb.php');
endwhile;
endif;
wp_reset_postdata();
die($out);
}
add_action('wp_ajax_nopriv_more_post_ajax', 'more_post_ajax');
add_action('wp_ajax_more_post_ajax', 'more_post_ajax');
And here is loadmore.js:
$(function() {
var ppp = 16; // Post per page
var pageNumber = 1;
function load_posts(){
pageNumber++;
var str = '&pageNumber=' + pageNumber + '&ppp' + ppp + '&action=more_post_ajax';
$.ajax({
type: "POST",
dataType: "html",
url: ajax_posts.ajaxurl,
data: str,
success: function(data){
var $data = $(data);
if($data.length){
$("#ajax-posts").append($data);
$("#more_posts").attr("disabled",false);
} else{
$("#more_posts").attr("disabled",true);
}
},
error : function(jqXHR, textStatus, errorThrown) {
$loader.html(jqXHR + " :: " + textStatus + " :: " + errorThrown);
}
});
return false;
}
$('#more_posts').unbind('click');
$("#more_posts").on("click",function(){ // When btn is pressed.
$("#more_posts").attr("disabled",true); // Disable the button, temp.
load_posts();
});
});
To make it work more dynamically with any taxonomy or combinations of taxonomies so this solutions would work not only in category.php but in any other case. For example JS could pass taxonomy term arguments where to fetch pposts from.
So first in your AJAX call we need to pass in the term where we want to load our posts from, lets say category is named milk. (And also lets make POST arguments more readable)
function load_posts(){
pageNumber++;
var str = {
pageNumber: pageNumber,
ppp: ppp,
term: 'milk',
action: 'more_post_ajax'
};
$.ajax({
type: "POST",
dataType: "html",
url: ajax_posts.ajaxurl,
data: str,
success: function(data){
var $data = $(data);
if($data.length){
$("#ajax-posts").append($data);
$("#more_posts").attr("disabled",false);
} else{
$("#more_posts").attr("disabled",true);
}
},
error : function(jqXHR, textStatus, errorThrown) {
$loader.html(jqXHR + " :: " + textStatus + " :: " + errorThrown);
}
});
return false;
}
In your PHP code
function more_post_ajax(){
$ppp = (isset($_POST["ppp"])) ? $_POST["ppp"] : 16;
$page = (isset($_POST['pageNumber'])) ? $_POST['pageNumber'] : 0;
$term = isset($_POST['term']) ? $_POST['term'] : 0;
header("Content-Type: text/html");
$args = array(
'suppress_filters' => true,
'posts_per_page' => $ppp,
'paged' => $page,
'tax_query' => array(
array(
'taxonomy' => 'category',
'field' => 'slug', // Depends whether JS passes you slug or ID of taxonomy term, in our case it is a slug
'terms' => array( $term ),
)
),
);
$loop = new WP_Query($args);
if ($loop -> have_posts()) : while ($loop -> have_posts()) : $loop -> the_post();
include(__DIR__.'/views/cat-post-thumb.php');
endwhile;
endif;
wp_reset_postdata();
die();
}
add_action('wp_ajax_nopriv_more_post_ajax', 'more_post_ajax');
add_action('wp_ajax_more_post_ajax', 'more_post_ajax');
Your WP_Query is now hardcoded to search from category taxonomy where posts have terms that match with the queried ones. You could change it to whatever you want, your not stuck with category taxonomy only if you change tax_query in your arguments. To be more secure you might want to check if that term exists in that taxonomy first.
The answer to your question seems to be in the documentation here.
Specifically, before making the call to WP_Query you need to specify the category you want. You're currently setting up the query here:
$args = array(
'suppress_filters' => true,
'posts_per_page' => $ppp,
'paged' => $page,
);
And you'll need to extend that to this:
$args = array(
'category_name' => $category
'suppress_filters' => true,
'posts_per_page' => $ppp,
'paged' => $page,
);
This means that your AJAX call will need to include the category you want (`$category) in the JSON, or you'll have to extract it from the page url. One way you could do this is:
$args = array(
'suppress_filters' => true,
'posts_per_page' => $ppp,
'paged' => $page,
);
if (isset($_POST["category"]){
$args['category_name'] = $_POST["category"];
}
Correspondingly, you'd need to update your AJAX call to have a category element:
var str = '&pageNumber=' + pageNumber + '&ppp' + ppp + '&action=more_post_ajax' + '&category=milk';
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