I found a function to automatically update the cart when the quantity of an item is changed, and it was working until WooCommerce's 3.2.0 updated (latest update 3.2.1). I'm pretty sure something changed within this code:
add_action('woocommerce_cart_updated', 'wac_update');
function wac_update() {
// is_wac_ajax: flag defined on wooajaxcart.js
if ( !empty($_POST['is_wac_ajax'])) {
$resp = array();
$resp['update_label'] = __( 'Update Cart', 'woocommerce' );
$resp['price'] = 0;
// render the cart totals (cart-totals.php)
ob_start();
do_action( 'woocommerce_after_cart_table' );
do_action( 'woocommerce_cart_collaterals' );
do_action( 'woocommerce_after_cart' );
$resp['html'] = ob_get_clean();
// calculate the item price
if ( !empty($_POST['cart_item_key']) ) {
$items = WC()->cart->get_cart();
$cart_item_key = $_POST['cart_item_key'];
if ( array_key_exists($cart_item_key, $items)) {
$cart_item = $items[$cart_item_key];
$_product = apply_filters( 'woocommerce_cart_item_product', $cart_item['data'], $cart_item, $cart_item_key );
$price = apply_filters( 'woocommerce_cart_item_subtotal', WC()->cart->get_product_subtotal( $_product, $cart_item['quantity'] ), $cart_item, $cart_item_key );
$resp['price'] = $price;
}
}
echo json_encode($resp);
exit;
}
}
My Javascript still working but here it is for a reference:
function refreshCart() {
jQuery('.cart-builder .qty').on('change', function(){
var form = jQuery(this).closest('form');
// emulates button Update cart click
jQuery("<input type='hidden' name='update_cart' id='update_cart' value='1'>").appendTo(form);
// plugin flag
jQuery("<input type='hidden' name='is_wac_ajax' id='is_wac_ajax' value='1'>").appendTo(form);
var el_qty = jQuery(this);
var matches = jQuery(this).attr('name').match(/cart\[(\w+)\]/);
var cart_item_key = matches[1];
form.append( jQuery("<input type='hidden' name='cart_item_key' id='cart_item_key'>").val(cart_item_key) );
// get the form data before disable button...
var formData = form.serialize();
jQuery("input[name='update_cart']").val('Updating...').prop('disabled', true);
jQuery.post( form.attr('action'), formData, function(resp) {
// ajax response
jQuery('.cart-collaterals').html(resp.html);
el_qty.closest('.cart_item').find('.product-subtotal').html(resp.price);
console.log(resp.test);
jQuery('#update_cart').remove();
jQuery('#is_wac_ajax').remove();
jQuery('#cart_item_key').remove();
jQuery("input[name='update_cart']").val(resp.update_label).prop('disabled', false);
},
'json'
);
});
}
I've been looking through the change log, https://github.com/woocommerce/woocommerce/blob/master/CHANGELOG.txt, but I can't find what would be conflicting now. Like I said, it was working perfectly before this updated.
Ok here is a simpler solution, I am just appending a script to the bottom of the cart page but you could also enqueue it with wp_enqueue_script function which is the best way. All it does it simulates the pressing of the update cart button.
function cart_update_qty_script() {
if (is_cart()) :
?>
<script type="text/javascript">
(function($){
$(function(){
$('div.woocommerce').on( 'change', '.qty', function(){
$("[name='update_cart']").trigger('click');
});
});
})(jQuery);
</script>
<?php
endif;
}
add_action( 'wp_footer', 'cart_update_qty_script' );
Related
First of all, I have no idea how old and / or deprecated (that's the word right?) this code is. My old developer (passed away) gave it to me well over two years ago, and now I am trying to make sense of it all.
Not being a programmer, I need help with two things, whereof the second part is the most important. When ALL products are removed from the checkout, redirect to the shop page.
This is the code I am using for adding qty and what not to the checkout.
add_filter( 'woocommerce_cart_item_name', 'jess_product_thumbnail_on_checkout_order_review', 20, 3 );
function jess_product_thumbnail_on_checkout_order_review( $product_name, $cart_item, $cart_item_key ) {
if ( is_checkout() ) {
$product = $cart_item['data'];
$thumbnail = $product->get_image(array(50, 50));
$image_html = '<div class="product-item-thumbnail">' . $thumbnail . '</div>';
$product_name_link = '' . $product_name . '';
$product_name = $image_html . $product_name_link;
}
return $product_name;
}
add_action( 'wp_footer', 'jess_product_image_css_checkout', 900 );
function jess_product_image_css_checkout(){
if (is_checkout()){ ?>
<style>
.product-item-thumbnail{float:left; padding-right:20px;}
.product-item-thumbnail img{margin:0!important;}
</style>
<?php
}}
add_filter('woocommerce_checkout_cart_item_quantity', 'jess_qty_change_remove_item_checkout_order_review', 1000, 3);
function jess_qty_change_remove_item_checkout_order_review( $quantity_html, $cart_item, $cart_item_key ) {
$_product = $cart_item['data'];
if ($_product->is_sold_individually()){
$product_quantity = sprintf('<input type="hidden" name="cart[%s][qty]" value="" />', $cart_item_key);
}else{
$product_quantity = woocommerce_quantity_input(
array(
'input_name' => "cart[{$cart_item_key}][qty]",
'input_value' => $cart_item['quantity'],
'max_value' => $_product->get_max_purchase_quantity(),
'min_value' => '1',
'class' => 'qtyinput',
'placeholder' => 'Qty',
'product_name' => $_product->get_name(),
),
$_product,
false
);
}
$cart = WC()->cart->get_cart();
foreach ($cart as $cart_key => $cart_value){
if ($cart_key == $cart_item_key){
$product_id = $cart_item['product_id'];
$_product = $cart_item['data'] ;
$remove_product = sprintf(
'Remove',
esc_url(wc_get_cart_remove_url($cart_key)),
__( 'Remove From My Order', 'woocommerce' ),
esc_attr( $product_id ),
esc_attr( $_product->get_sku() ),
esc_attr( $cart_item_key )
);
}}
return '<br><span class="product-quantity">' . sprintf( 'Qty: %s', $cart_item['quantity'] ) . ' / ' . $remove_product . '</span>'.$product_quantity.'';
}
add_action( 'wp_footer', 'refresh_checkout_on_quantity_change' );
function refresh_checkout_on_quantity_change() {
if (is_checkout()){ ?>
<script type="text/javascript">
<?php $admin_url = get_admin_url(); ?>
jQuery("form.checkout").on("change", "input.qty", function(){
var data = {
action: 'update_order_qty',
security: wc_checkout_params.update_order_review_nonce,
post_data: jQuery('form.checkout').serialize()
};
jQuery.post('<?php echo $admin_url; ?>' + 'admin-ajax.php', data, function(response){
jQuery('body').trigger('update_checkout');
});
});
</script>
<?php
}}
add_action( 'init', 'jess_load_ajax_checkout_qty_and_removal' );
function jess_load_ajax_checkout_qty_and_removal(){
if (!is_user_logged_in()){
add_action( 'wp_ajax_nopriv_update_order_qty', 'update_order_qty');
}else{
add_action( 'wp_ajax_update_order_qty', 'update_order_qty');
}}
function update_order_qty(){
$values = array();
parse_str($_POST['post_data'], $values);
$cart = $values['cart'];
foreach ($cart as $cart_key => $cart_value){
WC()->cart->set_quantity( $cart_key, $cart_value['qty'], false );
WC()->cart->calculate_totals();
woocommerce_cart_totals();
}
exit;
}
add_action( 'wp_footer', 'jess_remove_product_from_checkout_script' );
function jess_remove_product_from_checkout_script() { ?>
<script>
jQuery( function($){
if (typeof woocommerce_params === 'undefined')
return false;
console.log('defined');
$(document).on('click', 'tr.cart_item a.remove-product', function (e){
e.preventDefault();
var product_id = $(this).attr("data-product_id"),
cart_item_key = $(this).attr("data-cart_item_key"),
product_container = $(this).parents('.shop_table');
product_container.block({
message: null,
overlayCSS: {
cursor: 'none'
}
});
$.ajax({
type: 'POST',
dataType: 'json',
url: wc_checkout_params.ajax_url,
data: {
action: "product_remove",
product_id: product_id,
cart_item_key: cart_item_key
},
success: function (result) {
$('body').trigger('update_checkout');
console.log(result);
}
});
});
});
</script>
<?php
}
add_action('wp_ajax_product_remove', 'ajax_product_remove');
add_action('wp_ajax_nopriv_product_remove', 'ajax_product_remove');
function ajax_product_remove(){
ob_start();
foreach (WC()->cart->get_cart() as $cart_item_key => $cart_item) {
if($cart_item['product_id'] == $_POST['product_id'] && $cart_item_key == $_POST['cart_item_key'] ) {
WC()->cart->remove_cart_item($cart_item_key);
}
}
WC()->cart->calculate_totals();
WC()->cart->maybe_set_cart_cookies();
woocommerce_order_review();
$woocommerce_order_review = ob_get_clean();
}
Here is the modified code. I have added some comments where what is changed. This is tested on storefront theme and works.
//We need to load cart scripts
function checkout_woocommerce_scripts()
{
if ( is_checkout() ) wp_enqueue_script( 'wc-cart' );
}
add_action( 'wp_enqueue_scripts', 'checkout_woocommerce_scripts', 10 );
//When we remove all products from checkout will redirect to cart so we redirect to shop instead
//This also will work if we are on cart page and remove all products
add_action('template_redirect','redirect_cart_page');
function redirect_cart_page() {
if(is_cart() && WC()->cart->get_cart_contents_count() == 0 ):
wp_safe_redirect(wc_get_page_permalink( 'shop' ));
endif;
}
add_filter( 'woocommerce_cart_item_name', 'jess_product_thumbnail_on_checkout_order_review', 20, 3 );
function jess_product_thumbnail_on_checkout_order_review( $product_name, $cart_item, $cart_item_key ) {
if ( is_checkout() ) {
$product = $cart_item['data'];
$thumbnail = $product->get_image(array(50, 50));
$image_html = '<div class="product-item-thumbnail">' . $thumbnail . '</div>';
$product_name_link = '' . $product_name . '';
$product_name = $image_html . $product_name_link;
}
return $product_name;
}
add_action( 'wp_footer', 'jess_product_image_css_checkout', 900 );
function jess_product_image_css_checkout(){
if (is_checkout()){ ?>
<style>
.product-item-thumbnail{float:left; padding-right:20px;}
.product-item-thumbnail img{margin:0!important;}
</style>
<?php
}
}
//In this function all i did change is the class of the remove button from remove-product to product-remove
add_filter('woocommerce_checkout_cart_item_quantity', 'jess_qty_change_remove_item_checkout_order_review', 1000, 3);
function jess_qty_change_remove_item_checkout_order_review( $quantity_html, $cart_item, $cart_item_key ) {
$_product = $cart_item['data'];
if ($_product->is_sold_individually()){
$product_quantity = sprintf('<input type="hidden" name="cart[%s][qty]" value="" />', $cart_item_key);
}else{
$product_quantity = woocommerce_quantity_input(
array(
'input_name' => "cart[{$cart_item_key}][qty]",
'input_value' => $cart_item['quantity'],
'max_value' => $_product->get_max_purchase_quantity(),
'min_value' => '1',
'class' => 'qtyinput',
'placeholder' => 'Qty',
'product_name' => $_product->get_name(),
),
$_product,
false
);
}
$cart = WC()->cart->get_cart();
foreach ($cart as $cart_key => $cart_value){
if ($cart_key == $cart_item_key){
$product_id = $cart_item['product_id'];
$_product = $cart_item['data'] ;
$remove_product = sprintf(
'Remove',
esc_url(wc_get_cart_remove_url($cart_key)),
__( 'Remove From My Order', 'woocommerce' ),
esc_attr( $product_id ),
esc_attr( $_product->get_sku() ),
esc_attr( $cart_item_key )
);
}
}
return '<br><span class="product-quantity">' . sprintf( 'Qty: %s', $cart_item['quantity'] ) . ' / ' . $remove_product . '</span>'.$product_quantity.'';
}
// I have added wc_fragment_refresh to update your minicart when qty change.
add_action( 'wp_footer', 'refresh_checkout_on_quantity_change' );
function refresh_checkout_on_quantity_change() {
if (is_checkout()){ ?>
<script type="text/javascript">
<?php $admin_url = get_admin_url(); ?>
jQuery("form.checkout").on("change", "input.qty", function(){
var data = {
action: 'update_order_qty',
security: wc_checkout_params.update_order_review_nonce,
post_data: jQuery('form.checkout').serialize()
};
jQuery.post('<?php echo $admin_url; ?>' + 'admin-ajax.php', data, function(response){
jQuery('body').trigger( 'wc_fragment_refresh' );
jQuery('body').trigger('update_checkout');
});
});
</script>
<?php
}
}
// You dont need to wrap this in a function and do checks wp_ajax_nopriv runs for guests where wp_ajax runs for users
add_action( 'wp_ajax_nopriv_update_order_qty', 'update_order_qty');
add_action( 'wp_ajax_update_order_qty', 'update_order_qty');
function update_order_qty(){
$values = array();
parse_str($_POST['post_data'], $values);
$cart = $values['cart'];
foreach ($cart as $cart_key => $cart_value){
WC()->cart->set_quantity( $cart_key, $cart_value['qty'], false );
WC()->cart->calculate_totals();
woocommerce_cart_totals();
}
exit;
}
This is i think the better solution when we want to update cart items in checkout. Its all woocommerce core so it will perform and last longer than custom code for people who are not into coding.
Here is a video how its working https://webm.red/iV0t . It may get deleted after time.
//We need to load cart scripts
function checkout_woocommerce_scripts()
{
if ( is_checkout() ) wp_enqueue_script( 'wc-cart' );
}
add_action( 'wp_enqueue_scripts', 'checkout_woocommerce_scripts', 10 );
//If we want to redirect to shop page when cart or checkout get empty.
add_action('template_redirect','redirect_cart_page');
function redirect_cart_page() {
if(is_cart() && WC()->cart->get_cart_contents_count() == 0 ):
wp_safe_redirect(wc_get_page_permalink( 'shop' ));
endif;
}
//Load the cart form provided by woocommerce as shortcode.
// I will keep it outside the checkout form since its a form on its self.
// If we want we can extend the layout with modifying the checkout template.
add_action('woocommerce_before_checkout_form','checkout_cart_form');
function checkout_cart_form() {
echo do_shortcode('[woocommerce_cart]');
}
//Since we load cart form we dont need the coupon form twice
//Remove checkout coupon form comment this if you want to use this instead
remove_action( 'woocommerce_before_checkout_form', 'woocommerce_checkout_coupon_form', 10 );
//Remove cart coupon form
function hide_coupon_field_on_cart( $enabled ) {
if ( is_cart() ) { $enabled = false; } return $enabled;
}
//Uncomment this if you want to use this coupon form
// add_filter( 'woocommerce_coupons_enabled', 'hide_coupon_field_on_cart' );
//The scripts and styles we gonna use. Feel free to move them in your theme css js files (make sure they are loaded on checkout page)
add_action( 'wp_footer', 'checkout_styles_scripts');
function checkout_styles_scripts() {
?>
<style>
body.woocommerce-checkout button[name="update_cart"],
body.woocommerce-checkout input[name="update_cart"] {
display: none;
}
</style>
<script>
jQuery( function( $ ) {
let timeout;
$('.woocommerce').on( 'change keyup mouseup', 'input.qty', function(){
if ( timeout !== undefined ) {
clearTimeout( timeout );
}
timeout = setTimeout(function() {
$("[name='update_cart']").trigger("click"); // trigger cart update
}, 1000 ); // 1 second delay, half a second (500) seems comfortable too
});
} );
</script>
<?php
}
I am trying to remove WordPress posts from front end using AJAX.
My code removes post, but displays blank page with "success", when i want to just fade out this post without page reloading and displaying blank page.
PHP code:
<?php if( current_user_can( 'delete_post' ) ) : ?>
<?php $nonce = wp_create_nonce('my_delete_post_nonce') ?>
delete
<?php endif ?>
Functions.php code:
function my_frontend_script() {
wp_enqueue_script( 'my_script', get_template_directory_uri() . '/js/my_script.js', array( 'jquery' ), '1.0.0', true );
}
add_action( 'wp_enqueue_scripts', 'my_frontend_script' );
wp_localize_script( 'js/my_script.js', 'MyAjax2', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ), 'ajaxnonce' => wp_create_nonce('ajax-nonce') ) );
add_action( 'wp_ajax_my_delete_post', 'my_delete_post' );
function my_delete_post(){
$permission = check_ajax_referer( 'my_delete_post_nonce', 'nonce', false );
if( $permission == false ) {
echo 'error';
}
else {
wp_delete_post( $_REQUEST['id'] );
echo 'success';
}
die();
}
my_script.js code:
jQuery( document ).ready( function($) {
$(document).on( 'click', '.delete-post', function() {
var id = $(this).data('id');
var nonce = $(this).data('nonce');
var post = $(this).parents('.post:first');
$.ajax({
type: 'post',
url: MyAjax2.ajaxurl,
data: {
action: 'my_delete_post',
nonce: nonce,
id: id
},
success: function( result ) {
if( result == 'success7' ) {
post.fadeOut( function(){
post.remove();
});
}
}
})
return false;
})
})
The problem is page is reloading to a blank page with "success" text, when it should just fade out and remove post from current page, without reloading.
It looks like my_script.js is not even used at all :(
Any help much appreciated.
delete
it's reloading because it loads first the url in your href attribute, then executing your ajax-call. thats not what you want. you want to execute only the onclick. this should solve the problem. just put a # in your href
delete
or make buttons
<button data-id="<?php the_ID() ?>" data-nonce="<?php echo $nonce ?>" class="delete-post">delete</button>
edit: if it's still not working, it's because you got a typo here
if( result == 'success7' )
success7 instead of success
I'm adding a 'Remove' button next to each item in the Order via this function in functions.php:
add_action( 'woocommerce_order_item_meta_end', 'display_remove_order_item_button', 10, 3 );
function display_remove_order_item_button( $item_id, $item, $order ){
// Avoiding displaying buttons on email notification
if( ! ( is_wc_endpoint_url( 'view-order' ) || is_wc_endpoint_url( 'order-received' ) ) ) return;
if( isset($_POST["remove_item_$item_id"]) && $_POST["remove_item_$item_id"] == 'Remove this item' ){
wc_delete_order_item( $item_id );
}
echo '<form class="cart" method="post" enctype="multipart/form-data" style= "margin-top:12px;">
<input type="submit" class="button" name="remove_item_'.$item_id.'" value="Remove this item" />
</form>';
}
The issue is, after clicking the Remove button you then have to refresh the order page in order for the item to disappear.
I'd like that to happen automatically. I suppose I need to use Ajax to call the above function, but not quite sure how to do that.
Thanks in advance
Assuming your example is working, you'll change the function to look something like this:
add_action( 'woocommerce_order_item_meta_end', 'display_remove_order_item_button', 10, 3 );
function display_remove_order_item_button( $item_id, $item, $order ){
// Avoiding displaying buttons on email notification
if( ! ( is_wc_endpoint_url( 'view-order' ) || is_wc_endpoint_url( 'order-received' ) ) ) return;
echo '<form class="cart" method="post" enctype="multipart/form-data" style= "margin-top:12px;">
<input type="submit" id="remove-btn" data-id="'.$item_id.'" data-order="'.$order->get_order_number().'" class="button" name="remove_item_'.$item_id.'" value="Remove this item" />
</form>';
}
We gave the button a unique ID so we can detect clicks using jQuery. Notice data-id attribute, that's where we're passing $item_id. Now that display function is ready, we need to create an ajax call:
add_action('wp_head', 'ajax_call_remove_item');
function ajax_call_remove_item() {
?>
<script type="text/javascript" >
jQuery(document).ready(function($) {
$(document).on("click","#remove-btn",function(e) {
e.stopImmediatePropagation();
e.preventDefault();
// get data values from the button
var details = $(this).data();
var container = $(this).closest('td').parent('tr');
$(this).closest('td').append('<div id="loader">Data is loading</div>');
var data = {
action: 'remove_item',
// get id from data
id: details.id,
orderid: details.order,
};
$.post('<?php echo esc_url( home_url() ); ?>/wp-admin/admin-ajax.php', data, function(response) {
// display the response
$(container).empty();
$(container).html(response);
});
});
});
</script>
<?php
}
Now a function to handle POST data, delete the item and return a response:
add_action('wp_ajax_remove_item', 'remove_item_callback_wp');
add_action( 'wp_ajax_nopriv_remove_item', 'remove_item_callback_wp' );
function remove_item_callback_wp() {
$item_id = $_POST['id'];
$order_id = $_POST['orderid'];
$order = new WC_Order($order_id);
foreach ($order->get_items() as $order_item_id => $item){
if($order_item_id == $item_id){
wc_delete_order_item(absint($order_item_id));
}
}
echo "This items has been removed";
exit();
}
I'm working in a ecommerce with wordpresss and woocommerce, im adding to the shop page and category pages buttons that display the sizes for each product. with this code inside the theme function:
function woocommerce_variable_add_to_carts() {
global $product, $post;
$variations = $product->get_available_variations();
$product_sku = $product->get_sku();
$out = '<ul class="iconic-was-swatches iconic-was-swatches--loop iconic-was-swatches--text-swatch iconic-was-swatches--square">';
foreach ($variations as $key => $value) {
if (!empty($value['attributes'])) {
foreach ($value['attributes'] as $attr_key => $attr_value) {
$out .= '<li><a id="'.esc_attr($post->ID).'" data-quantity="1" data-product_id="'.esc_attr($post->ID).'" data-product_sku="'.$product_sku.'" class="iconic-was-swatch iconic-was-swatch--follow iconic-was-swatch--text-swatch add_to_cart_button">';
$out .= $attr_value . '</a></li>';
}
}
}
$out .= '</ul>';
echo $out;
}
add_action('woocommerce_before_shop_loop_item_title', 'woocommerce_variable_add_to_carts');
The idea is that when the users click in one of those sizes buttons the product is added to the cart directly in that page (shop page, category page). I made a custom endpoint to solve that from the answer provided here. I call the ajax function in the js file that Contains this:
$('.add_to_cart_button').on('click',function(){
jQuery.ajax({
url: WC_VARIATION_ADD_TO_CART.ajax_url,
type: "POST",
data: {
action : "customAdd_to_cart",
product_id : "697",
variation_id : "707",
quantity : 1,
variation : {
size : "s",
color: "pink"
}
},
success: function(){
alert('Ajax Success ');
}
});
});
(i'm using a specific product_id and variation_id for testing) then i add the callback function in the themes function page to add the products to the cart :
function customAddToCart() {
ob_start();
try {
$product_id = apply_filters( 'woocommerce_add_to_cart_product_id', absint( $data['product_id'] ) );
$quantity = empty( $data['quantity'] ) ? 1 : wc_stock_amount( $data['quantity'] );
$variation_id = isset( $data['variation_id'] ) ? absint( $data['variation_id'] ) : '';
$variations = $variation_id ? (array) get_variation_data_from_variation_id( $variation_id ) : null;
$product_status = get_post_status( $product_id );
$passed_validation = apply_filters( 'woocommerce_add_to_cart_validation', true, $product_id, $quantity, $variation_id, $variations, $cart_item_data );
if ( $passed_validation && WC()->cart->add_to_cart( $product_id, $quantity, $variation_id, $variations ) && 'publish' === $product_status ) {
do_action( 'woocommerce_ajax_added_to_cart', $product_id );
$res = getCartFragments();
} else {
$res = array(
'error' => true
);
}
return $res;
} catch (Exception $e) {
return new WP_Error('add_to_cart_error', $e->getMessage(), array('status' => 500));
}
}
add_action( 'wp_ajax_nopriv_woocommerce_add_variation_to_cart', 'customAddToCart' );
all this seems to work fine because doesn't give any error in console but the problems is that the variation Size in not added with the product that is selected just add the product. I dont know why this is happening, i even add an alert in the ajax success function
alert('Ajax Success ');
and that alert is displayed but the data it seems is not been sending like it should.
i want to know what i'm missing in any of this codes or it could be the js file and his location or i need to send another value in the a> builded in the first function above. i have try a lot things but the behavior still the same.
A quick scan over your code and I've noticed that the action you are calling with ajax is not correct. It should be woocommerce_add_variation_to_cart not customAdd_to_cart. Also it is common practice to use wp_send_json (or the more specific wp_send_json_success and wp_send_json_error functions) at the end of your ajax callback function so that you get a readable and sensible response in jQuery. Check out the following link if you have not used it before:
https://codex.wordpress.org/Function_Reference/wp_send_json
Hope this helps.
i am working on a plugin in wordpress to vote up a post or vote down using ajax.
Everything is working fine but the problem is am not able to disable the onclick eventhandler after first click so whenever someone voting a post , he can add vote multiple times. I want to ignore that so i should be able to vote only once. If i click on vote up then the voteup anchor tag should be disable and votedown anchor tag should be enable. At the same time if i click on the votedown anchor tag then votedown should be disable and voteup should be enable. Also i want to enable the voting feature only if the user is logged in the wordrpess.
I have a function to show a popup if the user is not logged in.
i.e login_open();
If user is not logged in and try to vote up then this function should execute login_open();
Otherwise user should be able to vote or downvote only once ..
Here is my code //
php
//Defining Base Paths
define('VOTEUPURL', WP_PLUGIN_URL."/".dirname( plugin_basename( __FILE__ ) ) );
define('VOTEUPPATH', WP_PLUGIN_DIR."/".dirname( plugin_basename( __FILE__ ) ) );
//Enqueue Script for the Admin Ajax and Cutom Js File
function voteme_enqueuescripts()
{
wp_enqueue_script('voteme', VOTEUPURL.'/js/voteup.js', array('jquery'));
wp_localize_script( 'voteme', 'votemeajax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
wp_localize_script( 'votedown', 'votedownajax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
}
add_action('wp_enqueue_scripts', voteme_enqueuescripts);
//Adding Vote up links to all the posts.
function voteme_getvotelink(){
$votemelink = "";
$post_ID = get_the_ID();
$votemecount = get_post_meta($post_ID, '_votemecount', true) != '' ? get_post_meta($post_ID, '_votemecount', true) : '0';
$link = $votemecount.' '.'Vote Up'.'';
$link .=' '.'Vote Down'.'';
$votemelink = '<div id="voteme-'.$post_ID.'">';
$votemelink .= '<span>'.$link.'</span>';
$votemelink .= '</div>';
return $votemelink;
}
//Function to get the count
function get_current_vote_count(){
$voteup_count = "";
$post_ID = get_the_ID();
$votemecount = get_post_meta($post_ID, '_votemecount', true) != '' ? get_post_meta($post_ID, '_votemecount', true) : '0';
$votelink = '<span class="vote_count">'. $votemecount .'</span>';
return $votelink;
die($votelink);
}
//Add Vote Function
function voteme_addvote()
{
$results = '';
global $wpdb;
$post_ID = $_POST['postid'];
$votemecount = get_post_meta($post_ID, '_votemecount', true) != '' ? get_post_meta($post_ID, '_votemecount', true) : '0';
$votemecountNew = $votemecount + 1;
update_post_meta($post_ID, '_votemecount', $votemecountNew);
$results.=$votemecountNew;
// Return the String
die($results);
}
// creating Ajax call of ADD VOTE for WordPress
add_action( 'wp_ajax_nopriv_voteme_addvote', 'voteme_addvote' );
add_action( 'wp_ajax_voteme_addvote', 'voteme_addvote' );
//Add Vote Function
function voteme_downvote()
{
$results = '';
global $wpdb;
$post_ID = $_POST['postid'];
$votemecount = get_post_meta($post_ID, '_votemecount', true) != '' ? get_post_meta($post_ID, '_votemecount', true) : '0';
$votemecountNew = $votemecount - 1;
update_post_meta($post_ID, '_votemecount', $votemecountNew);
$results.= $votemecountNew;
// Return the String
die($results);
}
// creating Ajax call of DOWN VOTE for WordPress
add_action( 'wp_ajax_nopriv_voteme_downvote', 'voteme_downvote' );
add_action( 'wp_ajax_voteme_downvote', 'voteme_downvote' );
//Javascript and Ajax Calls
function votemeaddvote(postId)
{
jQuery.ajax({
type: 'POST',
url: votemeajax.ajaxurl,
data: {
action: 'voteme_addvote',
postid: postId
},
success:function(data, textStatus, XMLHttpRequest){
var vote_count_id = jQuery('.vote_count');
jQuery(vote_count_id).html('');
jQuery('.vote_count').append(data);
var thisr = jQuery('.voter button:first-child')
thisr.disable = true;
// add any additional logic here
},
error: function(MLHttpRequest, textStatus, errorThrown){
alert(errorThrown);
}
});
}
function votemedownvote(postId)
{
jQuery.ajax({
type: 'POST',
url: votemeajax.ajaxurl,
data: {
action: 'voteme_downvote',
postid: postId
},
success:function(data, textStatus, XMLHttpRequest){
var vote_count_id = jQuery('.vote_count');
jQuery(vote_count_id).html('');
jQuery('.vote_count').append(data);
},
error: function(MLHttpRequest, textStatus, errorThrown){
alert(errorThrown);
}
});
}
//HTML For Adding Votes
<div class="voter">
<a onclick="votemeaddvote(<?php echo $post_ID; ?>);">VoteUp</a>
<a onclick="votemedownvote(<?php echo $post_ID; ?>)">Vote Down</a>
</div>
Simplely using .one() instead of .on()
Try something like this,
$(".voter a:last-child").one( "click", function() {
console.log("click");
var data = $(this).data();
console.log(data);
votemedownvote(data.id);
});
So what you could do is change some of your code
Change the html to this:
<div class="voter">
<a data-id="<?php echo $post_ID; ?>">VoteUp</a>
<a data-id="<?php echo $post_ID; ?>">Vote Down</a>
</div>
And change your javascript like this since you are using jquery:
$(".voter a").on( "click", function() {
console.log("click");
var data = $(this).data();
console.log(data);
votemeupvote(data.id);
$(this).off();
});
So var data get has the post id in json form to be sent.
Using "this" you are able to target this specific element and turn its on click off. I removed your on embedded click events because usually you want to bootstrap those triggers so you can turn them off, which was your problem.
You can do this by using jquery .on and .off methods.
Edit: Forgot to add your function call. I added it. I will also add how your votedown can work:
$(".voter a:last-child").on( "click", function() {
console.log("click");
var data = $(this).data();
console.log(data);
votemedownvote(data.id);
$(this).off();
});
Edit 2: Oh and I forgot to mention that this is only good for the front end. So in the backend you need someway to track if the person voted or not, maybe a table with user id, post id and voted true or false. That way you can track it when the ajax call comes and have php update the database.
Fiddle