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
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 searched all over here and the web but cant seem to get this to work - hopefully you all can help.
I am trying to setup product filters for WooCommerce on the category page (like filter products depending on color etc)
I have the ajax working but I have a shortcode that I want to display for each product and this doesnt work - any ideas how to get it to show?
Code below:
PHP
function ajax_filter_posts_scripts() {
// Enqueue script
wp_register_script('afp_script', plugins_url() . '/plugin-name/js/product-filter-ajax.js', false, null, false);
wp_enqueue_script('afp_script');
wp_localize_script( 'afp_script', 'afp_vars', array(
'afp_nonce' => wp_create_nonce( 'afp_nonce' ), // Create nonce which we later will use to verify AJAX request
'afp_ajax_url' => admin_url( 'admin-ajax.php' ),
)
);
}
add_action('wp_enqueue_scripts', 'ajax_filter_posts_scripts', 100);
JS
jQuery(document).ready(function($) {
$(".loading").hide();
var taxonomy = [];
var terms = [];
$('.filter-option input').click( function(event) {
var taxonomy_idx = $.inArray($(this).closest(".filter-title-wrapper").attr('data-attribute'), taxonomy);
if (taxonomy_idx == -1) {
taxonomy.push($(this).closest(".filter-title-wrapper").attr('data-attribute'));
} else {
taxonomy.splice(taxonomy_idx, 1);
}
var terms_idx = $.inArray($(this).val(), terms);
if (terms_idx == -1) {
terms.push($(this).val());
} else {
terms.splice(terms_idx, 1);
}
// Prevent default action - opening tag page
if (event.preventDefault) {
event.preventDefault();
} else {
event.returnValue = false;
}
// Get tag slug from title attirbute
var selecetd_taxonomy = taxonomy.toString();;
var selected_term = terms.toString();
var selected_term_speach = '\'' + selected_term.split(',').join('\',\'') + '\'';
console.log(selecetd_taxonomy);
console.log(selected_term_speach);
// After user click on tag, fade out list of posts
$('.products').fadeOut();
$(".loading").fadeIn();
data = {
action: 'filter_posts', // function to execute
afp_nonce: afp_vars.afp_nonce, // wp_nonce
taxonomy: selecetd_taxonomy, // selected tag
term: selected_term_speach,
};
$.post( afp_vars.afp_ajax_url, data, function(response) {
$(".loading").fadeOut();
if( response ) {
// Display posts on page
$('.products').html( response );
// Restore div visibility
$('.products').fadeIn();
};
});
});
});
PHP TO GET POSTS
// Script for getting posts
function ajax_filter_get_posts( $taxonomy, $term ) {
ob_start();
global $woocommerce, $product;
// Verify nonce
if( !isset( $_POST['afp_nonce'] ) || !wp_verify_nonce( $_POST['afp_nonce'], 'afp_nonce' ) )
die('Permission denied');
$taxonomy = $_POST['taxonomy'];
$term = $_POST['term'];
$term = str_replace("\\", '', $term);
// WP Query
$args = array(
'post_type' => 'product',
'post_status' => 'publish',
'posts_per_page' => -1,
);
if ($term == "''") {
}
else {
$args = array(
'tax_query' => array(
array(
'taxonomy' => $taxonomy,
'terms' => array($term),
'field' => 'slug',
'operator' => 'IN'
),
)
);
}
?>
<h1> <?php echo $term ?> </h1>
<?php
$query = new WP_Query( $args );
if ( $query->have_posts() ) : while ( $query->have_posts() ) : $query->the_post(); ?>
<li <?php wc_product_class(); ?>>
<?php echo do_shortcode('[product_shortcode]'); ?>
</li>
<?php
?>
<?php endwhile; ?>
<?php else: ?>
<h2>No posts found</h2>
<?php endif;
die();
return ob_get_clean();
}
add_action('wp_ajax_filter_posts', 'ajax_filter_get_posts');
add_action('wp_ajax_nopriv_filter_posts', 'ajax_filter_get_posts');
Excuse the messyness of the code, just trying to get it to work before I can start to neaten it up. Any advice on how to approach this in a better way please let me know.
Thanks and appreciate the help!
UPDATE-----
Tried to add the shortcode callback, but this doesnt work or I have the wrong code
add_action( 'init', function() {
ps_register_shortcode_ajax( 'ajax_filter_get_posts', 'ajax_filter_get_posts' );
} );
function ps_register_shortcode_ajax( $callable, $action ) {
if ( empty( $_POST['action'] ) || $_POST['action'] != $action )
return;
call_user_func( $callable );
}
WordPress Ajax calls don't have the access to whole WordPress environment and that's why your shortcode not working. Instead of calling the shortcode directly, call its callback. Refer https://wordpress.stackexchange.com/questions/53309/why-might-a-plugins-do-shortcode-not-work-in-an-ajax-request for more details.
Before asking question on SO, I searched a lot about what I needed to make a ajax request with WordPress. All my code and the request is working, but is not doing what I need it to do.
What I need to do is When I click at the buttom on checkout page "Novo Dependente", the information with the values to calculate total must update. "Total" value must be updated with a value which I defined at product post type page on admin panel. This value I already get, but the updating the value is real problem to me.
This is the page that I working.
This is the form, that shows up when i click the button, when i Toogle the checkbox I need to add the second value to the Total, another request with ajax.
And here my code goes
Obs: it's a plugin.
Here is the php code.
public function add_total_value()
{
if (! $_POST['action'] || $_POST['action'] !== 'add_total_value' ) :
echo json_encode(
array(
'status' => 'failed',
'message' => 'erro'
)
);
wp_die();
endif;
$woocommerce;
$quantidadeDependentes = $_POST['quantiaDependentes'];
//$produto_valor = WC()->cart->total;
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item )
{
$product = $cart_item['data'];
$item_id = $cart_item['product_id'];
$endereco_igual = get_post_meta( $item_id, 'adicional_mesmo', true);
$endereco_igual = str_replace(',', '.', $endereco_igual);
$endereco_igual = floatval( filter_var( $endereco_igual, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION ) );
$produtoValor = floatval( get_post_meta( $item_id, '_regular_price', true) );
$valorTotal = $produtoValor + ( $endereco_igual * $quantidadeDependentes );
WC()->cart->total = $valorTotal;
WC()->cart->calculate_totals();
wc_price($valorTotal);
}
echo json_encode(
array(
'status' => 'success',
'valorTotal' => wc_price($valorTotal)
));
wp_die();
}
My Ajax request
function contagemDependentes()
{
$contagem = jQuery('.woocommerce-dependentes-contagem');
var quantiaDependentes = jQuery('.woocommerce-dependentes-card').length;
if ( quantiaDependentes <= 0 ) {
var mensagemNumeroDependentes = 'Nenhum dependente informado';
} else if ( quantiaDependentes === 1 ) {
var mensagemNumeroDependentes = '1 dependente';
} else {
var mensagemNumeroDependentes = quantiaDependentes+' dependentes';
}
jQuery($contagem).html(mensagemNumeroDependentes);
var quantiaDependentes = jQuery('.woocommerce-dependentes-card').length + 1;
var dados = {
action: 'add_total_value',
quantiaDependentes: quantiaDependentes
};
jQuery.ajax({
type: 'POST',
url: custom_values.ajaxurl,
data: dados,
dataType: 'json',
success: function(response)
{
console.log(response);
if (response.status === 'success')
{
console.log(response.status);
console.log(response.valorTotal);
var html = "<tr class='order-total'>";
html += "<th>Total</th>";
html += "<td>";
html += response.valorTotal;
html += "</td>";
html += "</tr>";
jQuery( '.order-total' ).remove();
jQuery( 'tfoot' ).append( html );
jQuery( 'body' ).trigger( 'update_checkout' );
}
}
});
}
before function() in functions.php always must be such code
add_action('wp_ajax_your_function_name', 'your_function_name');
add_action('wp_ajax_nopriv_your_function_name', 'your_function_name');
So i'm trying to make a follow button in wp, and for some reason the ajax button isn't working right.
Here are the steps of what's supposed to happen
user clicks #followbtn
Ajax goes to $_POST action that = follow
php runs wp_set_object_terms( $user_id, $author_id, 'follow', true );
when that's done the function echo's "ok"
if the data = ok reload the page
For some reason the php isn't executing and the page isn't being reloaded.
add_action( 'wp_ajax_nopriv_jk-author-follow', 'jk_author_follow' );
add_action( 'wp_ajax_jk-author-follow', 'jk_author_follow' );
function jk_author_follow() {
$nonce = $_POST['nonce'];
if ( ! wp_verify_nonce( $nonce, 'ajax-nonce' ) )
die ( 'Nope!' );
if($_POST['action'] == "follow") {
$author_id = get_the_author_meta( 'nickname' ); // get authors name
$termId = get_term_by( 'slug', $author_id, 'follow' ); // get the term id from author
$termId = $termId->term_id;
$followers = get_objects_in_term( $termId, 'follow' ); // count followers in author term
$author_follow_count = count( $followers );
if ( is_user_logged_in() ) { // user is logged in
$user_id = get_current_user_id(); // current user
wp_set_object_terms( $user_id, $author_id, 'follow', true ); // Follow the author
echo "ok";
}
}
}
exit;
}
Front end button
function getAuthorFollowLink( $author_id ) {
$author = get_the_author_meta( 'nickname' );
$user_ID = get_current_user_id();
$termId = get_term_by( 'slug', $author, 'follow' ); // get the term id from author
$termId = $termId->term_id;
$followers = get_objects_in_term( $termId, 'follow' ); // count followers in author term
$count = count( $followers );
$output = 'Folllow '.$count.'';
return $output;
}
js
$(function(){
$('#followbtn').on('click', function(e){
e.preventDefault();
$('#followbtn').fadeOut(300);
$.ajax({
url: ajax_var.url,
type: 'post',
data: {'action': 'follow'},
success: function(data, status) {
if(data == "ok") {
location.reload();
}
},
error: function(xhr, desc, err) {
console.log(xhr);
console.log("Details: " + desc + "\nError:" + err);
}
}); // end ajax call
});
});
Try disabling this code
if ( ! wp_verify_nonce( $nonce, 'ajax-nonce' ) )
die ( 'Nope!' );
If You know the implications. You might want to learn more https://codex.wordpress.org/Function_Reference/wp_verify_nonce