Is it possible to count how many times a certain link in post has been clicked?
(for example purpose, let's say that the certain link has an ID named 'bla')
<a id="bla" href="#">download</a>
I got a feeling it should be possible by using custom-fields/post-meta (to keep the count), just like the ever-so-popular 'visitor count' trick. Unfortunately, I'm rather clueless about PHPs.
It could be done with ajax call that updates post meta field before the link is followed. Example below registers ajax action for users that are not logged in, and increases link_click_counter custom field by 1 on each click. Link must have id attribute countable_link. This is a basic example that works for only one link in post. To use it as a plugin create file like wp-content/plugins/click-counter /click-counter.php and copy-paste example code, or put the code in functions.php inside theme folder. First time the link is clicked, new custom field link_click_counter will be created for that post, and there you can track how many clicks link has.
HTML:
<a id="countable_link" href="#">download</a>
PHP:
<?php
/*
Plugin Name: Link Clicks Counter
*/
if ( is_admin() ) add_action( 'wp_ajax_nopriv_link_click_counter', 'link_click_counter' );
function link_click_counter() {
if ( isset( $_POST['nonce'] ) && isset( $_POST['post_id'] ) && wp_verify_nonce( $_POST['nonce'], 'link_click_counter_' . $_POST['post_id'] ) ) {
$count = get_post_meta( $_POST['post_id'], 'link_click_counter', true );
update_post_meta( $_POST['post_id'], 'link_click_counter', ( $count === '' ? 1 : $count + 1 ) );
}
exit();
}
add_action( 'wp_head', 'link_click_head' );
function link_click_head() {
global $post;
if( isset( $post->ID ) ) {
?>
<script type="text/javascript" >
jQuery(function ($) {
var ajax_options = {
action: 'link_click_counter',
nonce: '<?php echo wp_create_nonce( 'link_click_counter_' . $post->ID ); ?>',
ajaxurl: '<?php echo admin_url( 'admin-ajax.php' ); ?>',
post_id: '<?php echo $post->ID; ?>'
};
$( '#countable_link' ).on( 'click', function() {
var self = $( this );
$.post( ajax_options.ajaxurl, ajax_options, function() {
window.location.href = self.attr( "href" );
});
return false;
});
});
</script>
<?php
}
}
?>
One possible way is to redirect all through a common PHP gateway and from there, redirect to the original page you wanted to redirect using Header('Location: yourpage.html');
In the gateway PHP page count the number by incrementing a saved value by 1.
Related
I need help figuring out how to get the product id from the product page, to my function that opens a model box after a vimeo video ends.
inside that model box i need a variable with the product id. so i automatic can get the price of the product and insert the id inside a shortcode.
Hopefully someone can help, and feel free to ask, i will try to help if you need more information.
I have already tried the most common ideas, i could find.
global $product;
$id = $product->get_id();
or
global $post;
$id = $post->ID
or
global $product;
$id = $product->id;
I have tried in all the variations i could find.
if i use the first one, my function wont even work.
If i use the other 2, it only gives me a 0 as value.
// The javascript to call the function when video ends.
var iframe = document.querySelector("iframe");
var player = new Vimeo.Player(iframe);
player.on("ended", function() {
jQuery(document).ready(function($) {
var data = {
action: 'runThisPhpFunction',
};
jQuery.post(ajaxurl, data, function(popupfunction) {
$("#popup-box").html(popupfunction);
});
});
});
Next up is my function.
//Call Javascript video vimeo script to functions
function add_my_scripts() {
global $product;
$deps = array('jquery');
$in_footer = true;
wp_register_script( 'myjavascript', get_stylesheet_directory_uri() . '/js/myjavascript.js', array(), '1.0.0', true );
wp_enqueue_script( 'myjavascript', get_stylesheet_directory_uri() . '/js/myjavascript.js');
}
add_action( 'wp_enqueue_scripts', 'add_my_scripts' );
add_filter( 'widget_text', 'do_shortcode' );
add_action( 'wp_ajax_runThisPhpFunction', 'runThisPhpFunction' );
add_action( 'wp_ajax_nopriv_runThisPhpFunction', 'runThisPhpFunction' );
global $wpdb;
global $wp;
// THE FUNCTION WHERE I NEED THE ID FROM CURRENT PRODUCT PAGE AUTOMATIC
function runThisPhpFunction() {
global $product;
$product = wc_get_product();
$siteid = $product->ID;
//echo '<script>console.log($product);</script>';
echo '<script>document.getElementById("popup-box").classList.remove("hidden");</script>';
echo '<div class="modalheader">';
echo '<h3>Undskyld. Vi stoppede videoen!</h3>';
echo '</div>';
echo '<div class="modalcontent">';
echo $siteid, 'Men vi venter lige her, klar til at fortsætte når du har hentet Dankortet 😉';
echo '</div>';
}
As you are using javascript/jQuery/Ajax and as you need to get the product ID (which is the Post ID) in your Javascript code to pass it through Ajax to PHP, try the following revisited code instead:
add_action( 'wp_footer', 'custom_vimeo_player_script' );
function custom_vimeo_player_script() {
// Not in cart, checkout and my account pages
if( ! ( is_checkout() || is_cart() || is_account_page() ) ) :
?>
<script type="text/javascript">
jQuery(function($){
if (typeof wc_add_to_cart_params === 'undefined')
return false;
var iframe = document.querySelector("iframe"),
player = new Vimeo.Player(iframe);
player.on('ended', function(){
$.ajax({
type: 'POST',
url: wc_add_to_cart_params.ajax_url,
data: {
'action': 'enable_vimeo_popup_box',
'the_id': <?php echo get_the_id(); ?>,
},
success: function (result) {
// if popup-box has the class hidden
if( $("#popup-box").hasClass('hidden') && result ){
// remove the class hidden and add the html output
$("#popup-box").removeClass('hidden').html(result);
}
console.log(result);
},
});
});
});
</script>
<?php
endif;
}
// PHP: WordPress Ajax function triggered by Javascript
add_action( 'wp_ajax_enable_vimeo_popup_box', 'enable_vimeo_popup_box' );
add_action( 'wp_ajax_nopriv_enable_vimeo_popup_box', 'enable_vimeo_popup_box' );
function enable_vimeo_popup_box() {
if( isset($_POST['the_id']) ){
$post_id = (int) $_POST['the_id'];
echo '<div class="modalheader">
<h3>' . __("Undskyld. Vi stoppede videoen!") . '</h3>
</div><div class="modalcontent">' .
'<em>(post_id er ' . $post_id . ')</em> ' .
__("Men vi venter lige her, klar til at fortsætte når du har hentet Dankortet 😉") .
'</div>';
}
die();
}
Code goes in function.php file of your active child theme (or active theme). It should works.
I got help in this answer thread that allow to add an additional add-to-cart button that redirects to checkout. It works fine for simple products.
But how to make it work for variable products as well?
I've been trying myself, but no matter what I do, I break the site. I simply do not understand how to make this work with/ for variable products.
Here's the lightly changed code that works for simple products and which takes the quantity field into consideration:
add_action( 'woocommerce_after_add_to_cart_button', 'add_custom_addtocart_and_checkout' );
function add_custom_addtocart_and_checkout() {
global $product;
$addtocart_url = wc_get_checkout_url().'?add-to-cart='.$product->get_id();
$button_class = 'single_add_to_cart_button button alt custom-checkout-btn';
$button_text = __("Buy & Checkout", "woocommerce");
if( $product->is_type( 'simple' )) :
?>
<script>
jQuery(function($) {
var url = '<?php echo $addtocart_url; ?>',
qty = 'input.qty',
button = 'a.custom-checkout-btn';
// On input/change quantity event
$(qty).on('input change', function() {
$(button).attr('href', url + '&quantity=' + $(this).val() );
});
});
</script>
<?php
echo ''.$button_text.'';
endif;
}
Does anyone know how to get this working for variable products too?
Update 3
The following code will handle simple and variable products adding an additional Add to cart button that redirects to cart (with synchronized quantity).
The code works for simple and variable products as well.
add_action( 'woocommerce_after_add_to_cart_button', 'add_custom_addtocart_and_checkout' );
function add_custom_addtocart_and_checkout() {
global $product;
$addtocart_url = wc_get_checkout_url().'?add-to-cart='.$product->get_id();
$button_class = 'single_add_to_cart_button button alt custom-checkout-btn';
$button_text = __("Buy & Checkout", "woocommerce");
if( $product->is_type( 'simple' )) :
?>
<script>
jQuery(function($) {
var url = '<?php echo $addtocart_url; ?>',
qty = 'input.qty',
button = 'a.custom-checkout-btn';
// On input/change quantity event
$(qty).on('input change', function() {
$(button).attr('href', url + '&quantity=' + $(this).val() );
});
});
</script>
<?php
elseif( $product->is_type( 'variable' ) ) :
$addtocart_url = wc_get_checkout_url().'?add-to-cart=';
?>
<script>
jQuery(function($) {
var url = '<?php echo $addtocart_url; ?>',
vid = 'input[name="variation_id"]',
pid = 'input[name="product_id"]',
qty = 'input.qty',
button = 'a.custom-checkout-btn';
// Once DOM is loaded
setTimeout( function(){
if( $(vid).val() != '' ){
$(button).attr('href', url + $(vid).val() + '&quantity=' + $(qty).val() );
}
}, 300 );
// On input/change quantity event
$(qty).on('input change', function() {
if( $(vid).val() != '' ){
$(button).attr('href', url + $(vid).val() + '&quantity=' + $(this).val() );
}
});
// On select attribute field change event
$('.variations_form').on('change blur', 'table.variations select', function() {
if( $(vid).val() != '' ){
$(button).attr('href', url + $(vid).val() + '&quantity=' + $(qty).val() );
}
});
});
</script>
<?php
endif;
echo ''.$button_text.'';
}
Code goes in function.php file of your active child theme (or active theme). Tested and works.
I need the customer to be able to choose between add to cart and continue to shop and add to cart and get re-directed to the checkout. In other words, I'm adding a extra button to the product page.
Being new to WooCommerce, I'm struggling getting the qty input to function. It works fine if buying just one, but not when adding more than one (qty).
Also, I'm failing to understand how to add support for variable products, but that might be a separate question? (sorry if so).
Here's the code I'm using:
add_action( 'woocommerce_after_add_to_cart_button', 'add_content_after_addtocart' );
function add_content_after_addtocart() {
$current_product_id = get_the_ID();
$product = wc_get_product( $current_product_id );
$checkout_url = WC()->cart->get_checkout_url();
if( $product->is_type( 'simple' )) { ?>
<script>
jQuery(function($) {
$(".custom-checkout-btn").on("click", function() {
$(this).attr("href", function() {
return this.href + '&quantity=' + $('input.qty').val();
});
});
});
</script>
<?php
echo 'Buy & Checkout';
}
}
Any input on where I'm going wrong? All the help I can get is appreciated.
There are some mistakes in your code… Try the following:
add_action( 'woocommerce_after_add_to_cart_button', 'add_custom_addtocart_and_checkout' );
function add_custom_addtocart_and_checkout() {
global $product;
$addtocart_url = wc_get_checkout_url().'?add-to-cart='.$product->get_id();
$button_class = 'single_add_to_cart_button button alt custom-checkout-btn';
$button_text = __("Buy & Checkout", "woocommerce");
if( $product->is_type( 'simple' )) :
?>
<script>
jQuery(function($) {
var url = '<?php echo $addtocart_url; ?>',
qty = 'input.qty',
button = 'a.custom-checkout-btn';
// On input/change quantity event
$(qty).on('input change', function() {
$(button).attr('href', url + '&quantity=' + $(this).val() );
});
});
</script>
<?php
echo ''.$button_text.'';
endif;
}
Code goes in function.php file of your active child theme (or active theme). It should works.
As you guys know in CF7 on_sent_ok command deprecated and scheduled to be abolished by the end of 2017. So I decided to use the new script for redirecting my contact forms with this script provided by CF7
function add_this_script_footer(){ ?>
<script>
document.addEventListener( 'wpcf7mailsent', function( event ) {
location = 'http://websiteurl/thank-you';
}, false );
</script>
<?php }
add_action('wp_footer', 'add_this_script_footer');
but this applies to all contact forms. Since I am using quite different types of forms, may I know how can I exclude one of them from this redirection?
Try this script:
<script>
document.addEventListener( 'wpcf7mailsent', function( event ) {
if (event.detail.contactFormId != '123') { // This would exclude form with id 123
location = 'http://websiteurl/thank-you';
}
}, false );
</script>
Bonus tip: I often do it another way that makes it a bit more flexible. I put a <div class="do-some-action" data-something="foobar" style="display:none;"></div> in the CF7 form itself and then I can put this action in multiple forms if needed..
<script>
document.addEventListener( 'wpcf7mailsent', function( event ) {
var $cf = $( '#' + event.detail.id );
var $actionDiv = $cf.find( '.do-some-action' );
if ( $actionDiv && $actionDiv.length ) {
// Div with action class found
// We can also extract some data if needed
var something = $actionDiv.data( 'something' );
console.log( 'something = ' + something );
location = 'http://websiteurl/thank-you';
}
}, false );
</script>
I hope this helps!
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!