Exclude a dynamic value from cache with Wordpress Super Cache - php

I'm using the Super Cache plugin.
For some time I was looking for a solution, but without success. I need to disable the cache for one function in the file functions.php.
add_shortcode('custom_counter', 'example_shortcode');
function example_shortcode() {
// Get custom counter option value
$counter = get_option( 'wc-custom-counter' );
return '<span class="custom-counter">' . $counter . ' rub.</span>';
}
This is shortcode is used on the created custom page. It is necessary that the data output by this shortcode does not fall into the page cache.

Adapted from this old WSE thread, you will find below the complete way to make it working.
Here we display a spinner loading icon that will be replaced by the counter real non cached value through ajax. Javascript stays always active even in a cached page, so it can change anything needed on the page via Ajax or via any detected event. So there is no need to exclude anything in the plugin settings.
The replacement code:
// The shortcode
add_shortcode('custom_counter', 'customer_counter_shortcode');
function customer_counter_shortcode() {
// Start buffering
ob_start();
// Using woocommerce existing animated spinner gif icon
$loading_url = home_url( '/wp-content/plugins/woocommerce/assets/images/select2-spinner.gif' );
// Displaying a "Loading spinner icon + text to be replaced by Ajax value
echo '<span class="custom-counter">
<img id="loading-img" src="'.$loading_url.'" alt="Loading..." style="opacity:0.5; display:inline-block; vertical-align: middle;" />
<span style="opacity:0.5;"> ' . _("loading…") . '</span>
</span>';
?>
<script type="text/javascript">
jQuery( function($){
if (typeof woocommerce_params === 'undefined')
return false;
$.ajax({
type: 'POST',
url: woocommerce_params.ajax_url,
data: {
'action': 'custom_counter',
'custom-counter': true,
},
success: function (result) {
$('.custom-counter').text(result);
console.log('response: '+result); // just for testing | TO BE REMOVED
},
error: function(error){
console.log(error); // just for testing | TO BE REMOVED
}
});
});
</script>
<?php
return ob_get_clean(); // Return the buffered code
}
// The wordpress ajax hooked function (for logged in and non logged users)
add_action('wp_ajax_custom_counter', 'ajax_custom_counter');
add_action('wp_ajax_nopriv_custom_counter', 'ajax_custom_counter');
function ajax_custom_counter() {
if( isset($_POST['custom-counter']) && $_POST['custom-counter'] )
echo get_option( 'wc-custom-counter' ); // Get option value
exit();
}
Code goes in function.php file of your active child theme (or active theme). tested and works.

You cannot exclude a function from cache plugins. Instead you can exclude an URL (in WP Super Cache, go to 'Settings > WP Super Cache > Advanced' - 'Accepted Filenames & Rejected URIs' section).
So, call this function using AJAX instead calling directly and you can exclude the AJAX URL.
Here is the full code.
Add these in theme's functions.php:
add_action('wp_ajax_customer_counter', 'customer_counter_ajax_handler'); // wp_ajax_{action}
add_action('wp_ajax_nopriv_customer_counter', 'customer_counter_ajax_handler'); // wp_ajax_nopriv_{action}
function customer_counter_ajax_handler() {
// Get custom counter option value
$counter = get_option( 'wc-custom-counter' );
echo $counter . ' rub.';
}
Replace all your shortcodes [custom_counter] instances with <span class="customer_counter_shortcode"> </span>.
Add this script to theme's footer.php:
jQuery(function($){
$.ajax({
url : '<?php echo site_url(); ?>/wp-admin/admin-ajax.php', // AJAX handler
data : { action : 'customer_counter' },
type : 'POST',
success : function( $result ){
if( $result ) {
$('.customer_counter_shortcode').html($result);
}
}
});
});
You can then exclude the AJAX URL - /wp-admin/admin-ajax.php?action=customer_counter.

Related

Using wordpress action to modify div content

I'm trying to modify a div's content everytime when something is added to the woocommerce shopping cart. For this example the content is gonna be the current total cart value.
So first I created a simple plugin called "test-cart-value" which contains the following code:
<?php
function test_cart_value() {
echo "<div>" . WC()->cart->total . "</div>";
}
add_shortcode('test_cart_value_shortcode', 'test_cart_value');
This works fine, wherever I place the shortcode I get the current cart value after page load.
So, now I want this printed value to updated every time something is added to the cart, without reloading the page. The idea was to use the action hook woocommerce_cart_updated and call the function - so everytime something in the cart changes, the new cart value gets echoed:
function action_woocommerce_cart_updated() {
test_cart_value();
};
// add the action
add_action( 'woocommerce_cart_updated', 'action_woocommerce_cart_updated', 10, 0 );
The problem is, now I'm not able to dynamically add products to the shopping cart. Whenever I hit the "add to cart" button, the loading animation loads forever.
How to do this properly?
I was trying different approaches with Ajax and different Hooks, but so far nothing worked.
Any Ideas? Thanks in advance!
Edit:
So I tried this as my plugin code
function test_cart_value() {
echo "<div id='cart_test'>" . WC()->cart->total . "</div>";
}
add_shortcode('test_cart_value_shortcode', 'test_cart_value');
// define the actions for the two hooks created, first for logged in users and the next for logged out users
add_action("woocommerce_cart_updated", "cart_update");
// define the function to be fired for logged in users
function cart_update() {
$cart = WC()->cart->total;
$result['type'] = "success";
$result['new_cart'] = $cart;
$result = json_encode($result);
//if I uncomment the "die" function, the page won't load
// die();
}
// Fires after WordPress has finished loading, but before any headers are sent.
add_action( 'init', 'script_enqueuer' );
function script_enqueuer() {
// Register the JS file with a unique handle, file location, and an array of dependencies
wp_register_script( "test_script", plugin_dir_url(__FILE__).'test_script.js', array('jquery') );
// localize the script to your domain name, so that you can reference the url to admin-ajax.php file easily
wp_localize_script( 'test_script', 'myAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' )));
// enqueue jQuery library and the script you registered above
wp_enqueue_script( 'jquery' );
wp_enqueue_script( 'test_script' );
}
And my test_script.js code:
jQuery(document).ready( function() {
jQuery(".ajax_add_to_cart").click( function(e) {
e.preventDefault();
jQuery.ajax({
type : "post",
dataType : "json",
url : myAjax.ajaxurl,
data : {action: "cart_update"},
success: function(response) {
if(response.type == "success") {
jQuery("#cart_test").html(response.new_cart);
}
else {
alert("Your like could not be added");
}
}
});
});
});
So I thought that the cart_update() function should fire when I press the "ajax_add_to_cart" Button, but I get an error 400.
Any ideas?
Thanks!
made it work with woocommerce_add_to_cart_fragments.

How to get wp_ajax to work with jQuery $.post

Straight from WP Codex: http://codex.wordpress.org/AJAX_in_Plugins
I have this in my functions.php:
add_action( 'admin_footer', 'my_action_javascript' );
function my_action_javascript() {
?>
<script type="text/javascript" >
jQuery(document).ready(function($) {
var data = {
'action': 'my_action',
'whatever': 1234
};
// since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php
$.post(ajaxurl, data, function(response) {
alert('Got this from the server: ' + response);
});
});
</script>
<?php
}
add_action( 'wp_ajax_my_action', 'my_action_callback' );
function my_action_callback() {
global $wpdb; // this is how you get access to the database
$whatever = intval( $_POST['whatever'] );
$whatever += 10;
echo $whatever;
die(); // this is required to return a proper result
}
And I don't get a response. I do get an alert saying 'Got this from the server: ', but no response. What gives?
Running your code on two separate wordpress installs from within a plugin file (plugin-name.php) and from within functions.php in my theme, it returns the proper value both times. There do not seem to be any errors in your code either.
Is this the only javascript you're including in the admin area?

how to load wordpress comments using ajax when user scroll upto comment div

i have been trying to do this past 2 days but no success.
here is my code.
var elementOffse = $('#loadComments').offset().top;
var heigh = $(window).height();
$(window).scroll(function()
{
var scrollTopp = $(window).scrollTop();
if (scrollTopp >= (elementOffse - heigh) && loaded == 0)
{
loaded = 1;
$('#loadComments').html('Downloading...'); // Show "Downloading..."
$.ajax({
type: "GET",
url: "loadComments.php"
}).done(function(data) { // data what is sent back by the php page
$('#loadComments').html(data); // display data
});
}
});
in loadComments.php i call the function 'comments_template();'.
i want to load the comments in #loadComments after it is queried.
any help would be appreciated. thank you.
Wordpress has a built in AJAX handler, and using this ensures that your AJAX requests can access all the goodness of WP.
I can't say for sure without seeing logs, but if you are doing something with comments, it's likely that a WP core function is involved, and as a generic AJAX call won't include them, an error could be thrown.
Here is some JS that should do the trick -
var elementOffse = $('#loadComments').offset().top;
var heigh = $(window).height();
$(window).scroll(function(){
var scrollTopp = $(window).scrollTop();
if (scrollTopp >= (elementOffse - heigh) && loaded == 0){
loaded = 1;
$('#loadComments').html('Downloading...'); // Show "Downloading..."
var data = {
type: 'GET',
action: 'load-comments'
};
$.post(ajax_object.ajaxurl, data, function(response){
$('#loadComments').html(response);
});
}
});
PHP - Place this in functions.php (or any other custom included file if you wish) -
add_action( 'wp_ajax_nopriv_'.$_POST['ans_name'], 'my_ajax' ); // If user is not logged in
add_action( 'wp_ajax_'.$_POST['ans_name'], 'my_ajax' ); // If user is logged in
function my_ajax(){
{...do your comments stuff here...}
die(); // Required for a proper Wordpress AJAX result
}
Finally, to ensure AJAX requests for non-logged in users (the nopriv hook) are handeled correctly, add this to functions.php (or any other custom included file if you wish).
<?php
add_action('wp_head', 'plugin_set_ajax_url');
function plugin_set_ajax_url() {
?>
<script type="text/javascript">
var ajax_object = {};
ajax_object.ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
</script>
<?php
}
?>

How to send ajax request in wordpress without displaying zero

I am trying to send ajax request to another php page in wordpress. But every time it returns zero with other results.I need to remove the zero. I tried die(); to remove the zero. But after calling this, whole screen becomes blank. My code is below,
Jquery,
<script type="text/javascript">
function key_press(){
jQuery.ajax({
url : '<?php echo get_admin_url()?>admin-ajax.php',
type : 'POST',
data : jQuery('[name="ans_name"]').serialize()
}).done(function(result) {
// ta da
//alert("success");
jQuery("#widget_poll_id").html(result);
});
}
</script>
PHP,
add_action( 'wp_ajax_nopriv_'.$_POST['ans_name'], 'my_ajax' );
add_action( 'wp_ajax_'.$_POST['ans_name'], 'my_ajax' );
function my_ajax() {
echo $_POST['ans_name'];
die();
}
How could I get rid of from this situation ?
It's because your actions are not being called.
You need to declare the property action as below so that WP knows which action to call.
In your particular case you'll also have to declare ans_name (as opposed to data), so that $_POST['ans_name'] exists. I'm guessing that you wish this AJAX request to be called on many occasions by the fact that you used $_POST['ans_name'] in your hook name. If that is not the case, I suggest you use something static, as the hook could be called during other requests when you do not want it.
Finally, I've retrofitted your code with the WP AJAX handler, which will ensure all of the WP goodness that you may need during an AJAX request is included.
<script type="text/javascript">
function key_press(){
var data = {
url: '<?php echo get_admin_url()?>admin-ajax.php',
type: 'POST',
action: jQuery('[name="ans_name"]').serialize(),
ans_name: jQuery('[name="ans_name"]').serialize()
};
var myRequest = jQuery.post(ajax_object.ajaxurl, data, function(response){
alert('Got this from the server: ' + response);
});
myRequest.done(function(){
alert("success");
});
}
</script>
add_action( 'wp_ajax_nopriv_'.$_POST['ans_name'], 'my_ajax' );
add_action( 'wp_ajax_'.$_POST['ans_name'], 'my_ajax' );
function my_ajax(){
echo $_POST['ans_name'];
die(); // Required for a proper Wordpress AJAX result
}
Addition
To ensure AJAX requests for non-logged in users (the nopriv hook) are handeled correctly, add this to your functions.php file.
<?php
add_action('wp_head', 'plugin_set_ajax_url');
function plugin_set_ajax_url() {
?>
<script type="text/javascript">
var ajax_object = {};
ajax_object.ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
</script>
<?php
}
?>

AJAX: Send and retrieve a value with jquery post() and PHP, WordPress

I'm trying to make the following happen in a WordPress page:
User clicks on a "sort posts by" button
Value from the button is sent to sortFilter.php page
Current page is refreshed and uses the value posted in sortFilter.php to create a new loop.
On the initial page there is a tag that I want to load the data into:
<p id="sortFilter"></p>
Here is the code I'm using, and it doesn't seem to be working (nothing is being loaded into the #sortFilter p)
$(document).ready(function() {
setInterval(function(){
$("#sortFilter").load("http://<?php echo $_SERVER[HTTP_HOST]; ?>/sort-filter/");
},1000);
//Filter Categories
$.ajaxSetup({cache:true});
$('#byAuthorCtrl ul li').click( function() {
$.post("http://<?php echo $_SERVER[HTTP_HOST]; ?>/sort-filter/", {id: "testValue"}
);
});
});
then on sortFilter.php:
<?php
/*
Template Name: sortFilter
*/
$id = $_POST['id'];
echo $id;
?>
Right now I'm just using a test value to try to post to the page.
WordPress has built in AJAX capabilities. Send your ajax request to /wp-admin/admin-ajax.php using POST with the argument 'action':
jQuery(document).ready(function(){
jQuery.ajax({
type:'POST',
data:{
action:'my_unique_action',
id:'testValue'
},
url: "http://mysite/wp-admin/admin-ajax.php",
success: function(value) {
jQuery(this).html(value);
}
});
});
Then hook it in the plugin like this if you only want it to work for logged in users:
add_action('wp_ajax_my_unique_action','doMyCustomAjax');
or hook it like this to work only for non-logged in users:
add_action('wp_ajax_nopriv_my_unique_action','doMyCustomAjax');
Use both if you want it to work for everybody.
Here's the doAjax function, for example:
function doMyCustomAjax(){
$id = ( isset( $_POST['id'] ) ) ? $_POST['id'] : '';
if( empty( $id ) )
return;
echo $id;
}
Put that in functions.php too. That will return the id you send in AJAX.
admin-ajax.php uses some action names already, so make sure you look through the file and don't use the same action names, or else you'll accidentally try to do things like delete comments, etc.
EDIT
Put the add_action lines in the functions.php file. The admin-ajax.php file will run some functions and then runs the hook that your 'action' value makes, then kills the script. I've modified the code above to reflect this information.
Ok... sorry to use the Answer to add a comment, but it will be much easier to elaborate with the code display here.
So, I have the following in my functions.php:
add_action('wp_ajax_my_unique_action','doMyCustomAjax');
function doMyCustomAjax(){
$id = ( isset( $_POST['id'] ) ) ? $_POST['id'] : '';
if( empty( $id ) )
return;
echo $id;
}
the following script in footer.php to be executed on my category archive:
<script type="text/javascript">
$(document).ready(function() {
//Filter Categories
$.ajaxSetup({cache:true});
$('#byAuthorCtrl ul li').click( function() {
jQuery.ajax({
type:'POST',
data:{id:'my_unique_action'},
url: "http://www.theknotcollective.com/wp-admin/admin-ajax.php",
success: function(value) {
jQuery(this).html(value);
}
});
});
});
</script>
and the following at the top of my category.php:
<p id="sortFilter"><?php doMyCustomAjax(); ?></p>
Again my goal is to post that "id" variable once the link is clicked, then retrieve it once the page has been reloaded, in order to end up with a different loop on page refresh.
I'm new to ajax and this type of PHP function so I don't quite understand what's going on here, and obviously I'm missing something / doing something wrong. If you could elaborate a little I'd really appreciate it!
Thx!

Categories