In "woocommerce product finder" plugin, the first query field row display by default and if the user want to add another filed row based on product attributes, have to click on + button below the default row. How can I load all rows on page load without click event?
the php code:
public static function search_form( $atts = array(), $show_cat = false ) {
$action = get_permalink( wc_get_page_id( 'shop' ) );
$att_string = implode( $atts , ',' );
$html = '<form name="wc_product_finder" id="wc_product_finder" class="woocommerce" action="' . esc_url( $action ) . '" method="get">
<fieldset>
<legend>' . __( 'Product Finder','woocommerce-product-finder' ) . '</legend>
<input type="hidden" id="search_attributes" value="' . $att_string . '" />
<input type="hidden" id="show_cat" value="' . json_encode( $show_cat ) . '" />
<input type="hidden" name="adv_search" value="wc" />
<input type="hidden" name="post_type" value="product" />';
$html .= self::relation_dropdown();
if ( ( isset( $_GET['adv_search'] ) && 'wc' === $_GET['adv_search'] ) && isset( $_GET['tax'][0] ) ) {
foreach ( $_GET['tax'] as $row => $tax ) {
$html .= self::search_row( $row , $atts , $show_cat , true );
}
} else {
$html .= self::search_row( 0 , $atts , $show_cat );
}
$html .= '<div id="last_row" style="display:none;">0</div>
<span class="loader"> </span><span class="plus">+</span> <span class="text">' . __( 'Add row', 'woocommerce-product-finder' ) . '</span>';
$string = '';
if ( isset( $_GET['s'] ) ) {
$string = $_GET['s'];
}
$html .= '<div class="form-row form-row-first keywords"><label for="s">' . __( 'Keywords', 'woocommerce-product-finder' ) . '</label><input type="text" name="s" placeholder="' . __( 'Keywords', 'woocommerce-product-finder' ) . '" value="' . $string . '"/></div>';
if ( apply_filters( 'product_finder_show_price_slider', true ) ) {
$html .= self::price_slider();
}
$html .= '<div class="form-row form-row-wide form-row-submit"><input type="submit" class="button" value="' . __( 'Search' , 'woocommerce-product-finder' ) . '" /></div>
</fieldset>
</form>';
return $html;
}
and here is the jquery script:
jQuery( document ).ready( function() {
jQuery( '#wc_product_finder #add_row' ).css('display', 'block').click( function(e) {
e.preventDefault();
jQuery( '#add_row .loader' ).show();
jQuery( '#add_row .plus' ).hide();
var last_row = parseInt( jQuery( '#last_row' ).text() );
var next_row = last_row + 1;
var show_cat = jQuery( '#show_cat' ).val();
var search_attributes = jQuery( '#search_attributes' ).val();
jQuery.ajax({
type: "GET",
url: wc_product_finder_data.ajax_url,
data: 'action=wc_product_finder_add_row&row=' + next_row + '&show_cat=' + show_cat + '&search_attributes=' + search_attributes,
dataType: "html",
success: function( response ) {
if( response ) {
jQuery( '#last_row' ).before( response );
jQuery( '#last_row' ).text( next_row );
jQuery( '#search_row_' + next_row ).slideDown( 'fast' , function() {
jQuery( '#add_row .plus' ).show();
jQuery( '#add_row .loader' ).hide();
});
} else {
}
}
});
});
Thank you so much for your help.
Either invoke the click yourself or assign the function a name and invoke the function.
Either
jQuery( '#wc_product_finder #add_row' ).css('display', 'block').click( function(e) {
e.preventDefault();
jQuery( '#add_row .loader' ).show();
jQuery( '#add_row .plus' ).hide();
var last_row = parseInt( jQuery( '#last_row' ).text() );
var next_row = last_row + 1;
var show_cat = jQuery( '#show_cat' ).val();
var search_attributes = jQuery( '#search_attributes' ).val();
jQuery.ajax({
type: "GET",
url: wc_product_finder_data.ajax_url,
data: 'action=wc_product_finder_add_row&row=' + next_row + '&show_cat=' + show_cat + '&search_attributes=' + search_attributes,
dataType: "html",
success: function( response ) {
if( response ) {
jQuery( '#last_row' ).before( response );
jQuery( '#last_row' ).text( next_row );
jQuery( '#search_row_' + next_row ).slideDown( 'fast' , function() {
jQuery( '#add_row .plus' ).show();
jQuery( '#add_row .loader' ).hide();
});
} else {
}
}
});
});
// dispatch click yourself
jQuery( '#wc_product_finder #add_row' ).click()
or
// declare click handler
function handleClick(e) {
e && e.preventDefault();
jQuery( '#add_row .loader' ).show();
jQuery( '#add_row .plus' ).hide();
var last_row = parseInt( jQuery( '#last_row' ).text() );
var next_row = last_row + 1;
var show_cat = jQuery( '#show_cat' ).val();
var search_attributes = jQuery( '#search_attributes' ).val();
jQuery.ajax({
type: "GET",
url: wc_product_finder_data.ajax_url,
data: 'action=wc_product_finder_add_row&row=' + next_row + '&show_cat=' + show_cat + '&search_attributes=' + search_attributes,
dataType: "html",
success: function( response ) {
if( response ) {
jQuery( '#last_row' ).before( response );
jQuery( '#last_row' ).text( next_row );
jQuery( '#search_row_' + next_row ).slideDown( 'fast' , function() {
jQuery( '#add_row .plus' ).show();
jQuery( '#add_row .loader' ).hide();
});
} else {
}
}
});
// bind handler to click event
jQuery( '#wc_product_finder #add_row' ).css('display', 'block').click(handleClick)
// invoke function
handleClick()
Related
I am new with wordpress, I create a image uploader which followed a youtube video. But I found that it is only showed when I create new page. I can not add the uploader to the new page.
This is my code:
For php file
namespace image_uploader;
function register_metaboxes() {
add_meta_box('image_metabox','Image Uploader', __NAMESPACE__ . '\image_uploader_callback');
}
add_action('add_meta_boxes', __NAMESPACE__ . '\register_metaboxes');
function register_admin_script() {
wp_enqueue_script('wp_img_upload', plugins_url('image-upload.js', __FILE__), array('jquery', 'media-upload'), '1.0', true);
}
add_action('admin_enqueue_scripts', __NAMESPACE__ . '\register_admin_script');
function image_uploader_callback( $post_id ) {
wp_nonce_field( basename( __FILE__ ), 'image_nonce' );
$image_stored_meta = get_post_meta( $post_id );
?>
<div class="image-preview-wrapper">
<img id="image-preview" src="<?php if ( isset ( $image_stored_meta['image_meta'] ) ) echo $image_stored_meta['image_meta'][0]; ?>" style="max-width: 250px;">
<input type="hidden" name="image_meta" id="image-meta">
<button type="button" id="image-upload-button" class="button">Upload Image</button>
<button type="button" id="image-remove-button" class="button">Remove Image</button>
</div>
<button id="nextPage">move to the next page</button>
<?php
}
function save_custom_meta( $post_id, $post, $update ) {
// Checks save status
$is_autosave = wp_is_post_autosave( $post_id );
$is_revision = wp_is_post_revision( $post_id );
$is_valid_nonce = ( isset( $_POST[ 'image_nonce' ] ) && wp_verify_nonce( $_POST[ 'image_nonce' ], basename( __FILE__ ) ) ) ? 'true' : 'false';
// Exits script depending on save status
if ( $is_autosave || $is_revision || !$is_valid_nonce ) {
return;
}
// Checks for input and sanitizes/saves if needed
if( isset( $_POST[ 'image_meta' ] ) ) {
$image_data = json_decode( stripslashes( $_POST[ 'image_meta' ] ), true );
if(is_object($image_data)) {
$image_data = array(
'id' => intval($image_data[0]->id),
'src' => esc_url_raw($image_data[0]->url),
'width' => intval($image_data[0]->width),
'height' => intval($image_data[0]->height)
);
} else {
$image_data=[];
}
update_post_meta( $post_id, 'image_meta', sanitize_text_field( $_POST[ 'image_meta' ] ) );
}
}
add_action( 'save_post', __NAMESPACE__ . '\save_custom_meta', 10, 3 );
add_filter('wp_handle_upload_prefilter','tc_handle_upload_prefilter');
function tc_handle_upload_prefilter($file)
{
$img=getimagesize($file['tmp_name']);
$fixedSize = array('width' => '400', 'height' => '600');
$width= $img[0];
$height =$img[1];
if ($width != $fixedSize['width'] )
return array("error"=>"Image dimensions are too small. Minimum width is {$fixedSize['width']}px. Uploaded image width is $width px");
elseif ($height != $fixedSize['height'])
return array("error"=>"Image dimensions are too small. Minimum height is {$fixedSize['height']}px. Uploaded image height is $height px");
else
return $file;
}
for js file
addEventListener("DOMContentLoaded", function() {
console.log('DOMContentLoaded');
var addButton = document.getElementById('image-upload-button');
var removeButton = document.getElementById('image-remove-button');
var image = document.getElementById('image-preview');
var hidden = document.getElementById('image-meta');
var next = document.getElementById('nextPage');
image.setAttribute('required', 'required');
var uploader = wp.media({
title: 'Select an image',
button: {
text: 'Use this image'
},
multiple: false
});
addButton.addEventListener('click', function(e) {
e.preventDefault();
if(uploader) {
uploader.open();
}
});
uploader.on('select', function() {
var attachment = uploader.state().get('selection').first().toJSON();
image.setAttribute('src', attachment.url);
hidden.setAttribute('value', JSON.stringify({id: attachment.id, url: attachment.url}));
});
removeButton.addEventListener('click', function(e) {
image.removeAttribute('src');
hidden.removeAttribute('value');
});
next.addEventListener('click', function(e) {
e.preventDefault();
window.location.href = "http://google.com";
});
});
I did a lot of research, but still can not figure it out.
Please give me some advices, thanks a lot!
I'm trying to create an add to cart with Ajax. I have a custom style attribute that I display on the front. The Add to cart button is in a form that has hidden input fields that collect information about the product, such as product_id, quantity, variation_id, etc. it looks like this:
<form class="add-to-cart-form cubestheme-add-to-cart-form" action="" name="quantity">
<input type="hidden" name="product_name" value="<?php echo $product->get_name(); ?>">
<input type="hidden" name="product_id" value="<?php echo $product->get_id(); ?>">
<input type="hidden" class="variation_id" name="variation_id" value="">
<input type="hidden" name="qty" id="qty" value="1" min="1" inputmode="numeric" pattern="[0-9]*">
<button class="btn add-to-cart btn-single-product added" name="add-to-cart" value="" type="submit">Add to cart</button>
</form>
My ajax call looks like this, I collect information ie product attributes and I should generate variation_id using those attributes, the ajax call looks like this:
$(document).on('submit', 'form.cubestheme-add-to-cart-form', function (e) {
e.preventDefault();
let product_id = $(this).find("input[name='product_id']").val();
let cart_button = $('form.cubestheme-add-to-cart-form').find(
"button[name='add-to-cart']"
);
let variation_id = 0;
let tsize = '';
let bsize = '';
let color = '';
let size = '';
if ($('a.pa_top-size.active').length)
tsize = $('a.pa_top-size.active').attr('data-id');
if ($('a.pa_bottom-size.active').length)
bsize = $('a.pa_bottom-size.active').attr('data-id');
if ($('a.pa_color.active').length)
color = $('a.pa_color.active').attr('data-id');
if ($('a.pa_size.active').length)
size = $('a.pa_size.active').attr('data-id');
jQuery.ajax({
type: 'post',
url: wc_add_to_cart_params.ajax_url,
data: {
action: 'woocommerce_ajax_select_variation',
product_id: product_id,
tsize: tsize,
bsize: bsize,
size: size,
color: color,
},
beforeSend: function (response) {
cart_button.removeClass('added').addClass('loading');
$('.se-pre-con').fadeIn('fast');
},
complete: function (response) {
cart_button.addClass('added').removeClass('loading');
$('.se-pre-con').fadeOut('fast');
},
success: function (response) {
if (response.error & response.product_url) {
return;
} else {
variation_id = response.variation_id;
$('form.cubestheme-add-to-cart-form')
.find("input[name='variation_id']")
.val(response.variation_id);
let product_id = $('form.cubestheme-add-to-cart-form')
.find("input[name='product_id']")
.val();
let product_qty = $('form.cubestheme-add-to-cart-form')
.find("input[name='qty']")
.val();
product_qty = parseInt(product_qty);
let cart_button = $('form.cubestheme-add-to-cart-form').find(
"button[name='add-to-cart']"
);
let product_sku = $('form.cubestheme-add-to-cart-form')
.find("input[name='sku']")
.val();
let data = {
action: 'woocommerce_ajax_add_to_cart',
product_id: product_id,
product_sku: product_sku,
quantity: product_qty,
variation_id: response.variation_id,
};
jQuery.ajax({
type: 'post',
url: wc_add_to_cart_params.ajax_url,
data: data,
beforeSend: function (response) {
cart_button.removeClass('added').addClass('loading');
$('.se-pre-con').fadeIn('fast');
},
complete: function (response) {
cart_button.addClass('added').removeClass('loading');
$('.se-pre-con').fadeOut('fast');
},
success: function (response2) {
if (response2.error & response2.product_url) {
$('.error-message').css('display', 'block');
window.location = response2.product_url;
return;
} else {
$('.success-message').css('display', 'block');
//$(".cubestheme-cart-items").html(response.cart_items);
$('.cubestheme-cart-items-counter').html(
response2.items_counter
);
//$(".cubestheme-cart-total").html(response.cart_total);
setTimeout($('.success-message').css('display', 'none'), 7000);
}
},
});
}
},
});
});
My add to cart logic works great.
This is my ajax.php action that is not working properly for me:
function woocommerce_ajax_select_variation() {
$status = "failed";
$variation_id = 0;
$variation_price = 0;
$product_id = apply_filters('woocommerce_add_to_cart_product_id', absint($_POST['product_id']));
$_att_names = $_POST['att_names']; $att_names = explode("|", $_att_names);
$_att_vals = $_POST['att_vals']; $att_vals = explode("|", $_att_vals);
$selected_variation = array();
for($i = 0; $i < count($att_names); $i++) { $selected_variation[$att_names[$i]] = $att_vals[$i]; };
$product = wc_get_product( $product_id );
$variations = $product->get_available_variations();
foreach($variations as $variation){
$attributes = $variation['attributes'];
$check = 0;
foreach($attributes as $k => $v){
if($selected_variation[$k] != $v){
$check++;
}
}
if($check == 0) {
$variation_id = $variation['variation_id'];
$variation = new WC_Product_Variation( $variation_id );
$variation_price = $variation->get_price_html();
$status = "done";
break;
}
}
echo wp_send_json( array("var" => $att_names, "status" => $status, "variation_id" => $variation_id, "variation_price" => $variation_price) );
die();
}
The problem is that I cannot collect the attribute and generate the variation_id that I need.
Stuck at the stage where it is necessary for the user to be able to add to the cart at once all sizes of goods of a certain color.
Because of the complexity, I decided to try another interaction, how the user can choose, for example, a color, and then 44, 46, 48 product sizes, that is, a multi selection of several attributes.
Or where to dig?
https://docs.google.com/document/d/1RrUr81o6V7i1a1mz9wat66STxS5mMijG84kovXrl5mQ/edit?usp=sharing
There is a code that allows you to do this, but I can't figure it out.
Let me remind you of vukomers out of the box.
function.php
function new_scripts() {
// Scripts
wp_enqueue_script( 'popper-js', 'https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js', array( 'jquery' ), '1.14.7', true );
wp_enqueue_script( 'bootstrap-js', 'https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js', array( 'jquery' ), '4.3.1', true );
wp_enqueue_script( 'aaa-js', content_url() . '/themes/milena/js/ajax_add_to_cart.js', array( 'jquery' ), '4.3.1', true );
wp_localize_script( 'bootstrap-js', 'ajax_object',
array(
'url' => admin_url('admin-ajax.php'),
)
); }
add_action( 'wp_enqueue_scripts', 'new_scripts' );
add_action( 'woocommerce_before_add_to_cart_button', 'action_woocommerce_before_variations_form', 10, 0 );
function action_woocommerce_before_variations_form( ) {
global $product;
$variations = $product->get_available_variations();
$variation_ids = '';
foreach ($variations as $variation_one) {
$variation_ids .= $variation_one['variation_id'].':';
}
?>
<div class="checkbox_wrapp" >
<div class="checkbox_sizes_all">
<input type="checkbox" id="check-sizes-all" value="<?php echo $variation_ids; ?>">
<label for="check-sizes-all">
<span class="option-name">Весь размерный ряд</span>
</label>
</div>
<div id="all_into_cart" style="">В корзину</div>
</div>
<?php
};
add_action('wp_ajax_ajax_cstm_add_to_cart', 'ajax_cstm_add_to_cart' );
add_action('wp_ajax_nopriv_ajax_cstm_add_to_cart', 'ajax_cstm_add_to_cart' );
function ajax_cstm_add_to_cart() {
global $woocommerce;
$variations = $_POST['variations_ids'];
$variations_kol = $_POST['variations_kol'];
$variations_ids = explode( ":", $variations );
foreach ($variations_ids as $variation) {
$woocommerce->cart->add_to_cart( $variation, $variations_kol );
}
$return = array(
'success' => true,
);
wp_send_json($return);}'
JavaScript
jQuery(document).ready(function(){
jQuery("#check-sizes-all").on("click", function () {
if( jQuery('#all_into_cart').hasClass('active') ){
jQuery('#all_into_cart').removeClass('active');
jQuery('#all_into_cart').fadeOut(10);
} else{
jQuery('#all_into_cart').fadeIn(10);
jQuery('#all_into_cart').addClass('active');
}
});
jQuery("#all_into_cart").on("click", function () {
if( jQuery('#check-sizes-all').prop("checked") == true ){
var variations_ids = jQuery('#check-sizes-all').val();
var variations_kol = jQuery('.product .cart .quantity .input-text').val();
let data = {
action: "ajax_cstm_add_to_cart",
variations_ids: variations_ids,
variations_kol: variations_kol,
};
jQuery.ajax({
url: ajax_object.url,
data: data,
dataType: 'JSON',
type: "POST",
success: function (response) {
if (response) {
location.reload();
}
}
});
}
});
});
When Ajax add to cart functionality is active on my WooCommerce store, on Ajax add to cart first click It shows a checked icon symbol like:
The code below changes the add to button cart text to "Seçildi !" if product is already in to cart, only after refreshing page like:
//Rename the button on the Product page
add_filter( 'woocommerce_product_single_add_to_cart_text', 'ts_product_add_cart_button' );
function ts_product_add_cart_button( $label ) {
foreach( WC()->cart->get_cart() as $cart_item_key => $values ) {
$product = $values['data'];
if( get_the_ID() == $product->get_id() ) {
$label = __('Seçildi !', 'woocommerce');
}
}
return $label;
}
//Rename the button on the Shop page
add_filter( 'woocommerce_product_add_to_cart_text', 'ts_shop_add_cart_button', 99, 2 );
function ts_shop_add_cart_button( $label, $product ) {
if ( $product->get_type() == 'simple' && $product->is_purchasable() && $product->is_in_stock() )
{
foreach( WC()->cart->get_cart() as $cart_item_key => $values ) {
$_product = $values['data'];
if( get_the_ID() == $_product->get_id() ) {
$label = __('Seçildi !', 'woocommerce');
}
}
}
return $label;
}
But if you don't refresh the page the button remains like before with the checked icon symbol.
What I would like is to change add to cart button with the quantity that has been added for this product like:
Is this possible? What do I need to change? Any help is appreciated.
You can use WC woocommerce_product_add_to_cart_text action hook and you can get wc cart loop through all products and compare path second params $prodcuct object. check below code. code will go active theme functions.php file.
function change_add_to_cart_text_if_product_already_in_cart( $add_to_cart_text, $product ) {
if ( WC()->cart ) {
$cart = WC()->cart; // Get cart
if ( ! $cart->is_empty() ) {
foreach ( $cart->get_cart() as $cart_item_key => $cart_item ) {
$_product_id = $cart_item['product_id'];
if ( $product->get_id() == $_product_id ) {
$add_to_cart_text = '('.$cart_item['quantity'].')'.' Already in cart';
break;
}
}
}
}
return $add_to_cart_text;
}
add_filter( 'woocommerce_product_add_to_cart_text', 'change_add_to_cart_text_if_product_already_in_cart', 10, 2 );
add_filter( 'woocommerce_product_single_add_to_cart_text', 'change_add_to_cart_text_if_product_already_in_cart', 10, 2 );
Updated ( as per OP request how to change text quick on click with quantity ).
There is two way You can do this.
you can use woocommerce_loop_add_to_cart_args and add product qty attribute and based on that you can display.
function add_product_qty( $args, $product ){
if ( WC()->cart ) {
$cart = WC()->cart; // Get cart
if ( ! $cart->is_empty() ) {
foreach ( $cart->get_cart() as $cart_item_key => $cart_item ) {
$_product_id = $cart_item['product_id'];
if ( $product->get_id() == $_product_id ) {
$args['attributes']['data-product-qty'] = $cart_item['quantity'];
}else{
$args['attributes']['data-product-qty'] = 0;
}
}
}else{
$args['attributes']['data-product-qty'] = 0;
}
}
return $args;
}
add_filter( 'woocommerce_loop_add_to_cart_args', 'add_product_qty', 10, 2 );
add_action( 'wp_footer', 'ajax_button_text_quick_change_js_script' );
function ajax_button_text_quick_change_js_script() {
?>
<script>
(function($) {
$(document.body).on('click', '.ajax_add_to_cart', function(event){
$this = $(this);
var product_qty = parseInt($this.attr('data-product-qty')) + 1;
$this.attr('data-product-qty',product_qty);
var buttonText = '<span class="add_to_cart_text product-is-added">('+product_qty+') Already in cart</span><i class="cart-icon pe-7s-cart"></i>';
$this.html(buttonText).attr('data-tip','('+product_qty+') Already in cart');
});
})(jQuery);
</script>
<?php
}
You can use added_to_cart jQuery event that triggers after adding to the cart you call ajax and get add_to_cart_text in response.
add_action( 'wp_footer', 'ajax_button_text_js_script' );
function ajax_button_text_js_script() {
?>
<script>
(function($) {
$(document.body).on('added_to_cart', function(event, fragments, cart_hash, button){
var product_id = button.data('product_id'),
product_qty = button.data('quantity');
button.addClass('loading');
$.ajax({
url: "<?php //echo admin_url('admin-ajax.php'); ?>",
method: 'POST',
data:{action:'change_add_to_cart_text',product_id:product_id},
dataType: "json",
success: function( response ){
var buttonText = '<span class="add_to_cart_text product-is-added">'+response.data.button_text+'</span><i class="cart-icon pe-7s-cart"></i>';
button.html(buttonText).attr('data-tip',response.data.button_text);
button.removeClass('loading');
},error: function (jqXHR, exception) {
var msg = '';
if (jqXHR.status === 0) {
msg = 'Not connect.\n Verify Network.';
} else if (jqXHR.status == 404) {
msg = 'Requested page not found. [404]';
} else if (jqXHR.status == 500) {
msg = 'Internal Server Error [500].';
} else if (exception === 'parsererror') {
msg = 'Requested JSON parse failed.';
} else if (exception === 'timeout') {
msg = 'Time out error.';
} else if (exception === 'abort') {
msg = 'Ajax request aborted.';
} else {
msg = 'Uncaught Error.\n' + jqXHR.responseText;
}
console.log(msg);
},
});
});
})(jQuery);
</script>
<?php
}
add_action('wp_ajax_change_add_to_cart_text', 'change_add_to_cart_text');
add_action('wp_ajax_nopriv_change_add_to_cart_text', 'change_add_to_cart_text');
function change_add_to_cart_text(){
$product_id = $_POST['product_id'];
if ( WC()->cart ) {
$cart = WC()->cart; // Get cart
if ( ! $cart->is_empty() ) {
foreach ( $cart->get_cart() as $cart_item_key => $cart_item ) {
$_product_id = $cart_item['product_id'];
if ( $product_id == $_product_id ) {
$add_to_cart_text = '('.$cart_item['quantity'].')'.' Already in cart';
break;
}
}
}
}
wp_send_json_success(array(
'button_text' => $add_to_cart_text
));
}
This below code only for OP site.
add_filter( 'woocommerce_loop_add_to_cart_link', 'custom_add_quantity_fields', 99, 2 );
function custom_add_quantity_fields($html, $product) {
//add quantity field only to simple products
if ( $product && $product->is_type( 'simple' ) && $product->is_purchasable() && $product->is_in_stock() && ! $product->is_sold_individually() ) {
if ( WC()->cart ) {
$cart = WC()->cart; // Get cart
if ( ! $cart->is_empty() ) {
foreach ( $cart->get_cart() as $cart_item_key => $cart_item ) {
$_product_id = $cart_item['product_id'];
if ( $product->get_id() == $_product_id ) {
$data_product_qty = $cart_item['quantity'];
}else{
$data_product_qty = 0;
}
}
}else{
$data_product_qty = 0;
}
}
//rewrite form code for add to cart button
$html = '<form action="' . esc_url( $product->add_to_cart_url() ) . '" class="cart" method="post" enctype="multipart/form-data">';
$html .= woocommerce_quantity_input( array(), $product, false );
$html .= '<button type="submit" data-quantity="1" data-product_id="' . $product->get_id() . '" class="button alt ajax_add_to_cart add_to_cart_button product_type_simple" data-product-qty="'.$data_product_qty.'">' . esc_html( $product->add_to_cart_text() ) . '</button>';
$html .= '</form>';
}
return $html;
}
Tested and works.
I'm a beginner in jQuery-Ajax so please bear with me. My Ajax response does not seem to load but my changes are being saved. but gives me this error on admin-ajax.php "call_user_func() expects parameter 1 to be a valid callback, function '_update_post_ter_count' not found or invalid function name".
Here is my function, could you point what i'm doing wrong?
add_action( 'wp_ajax_nopriv_save_sort', 'ccmanz_save_reorder' );
add_action('wp_ajax_save_sort','ccmanz_save_reorder');
function ccmanz_save_reorder() { //checking
//verify user intent
check_ajax_referer( 'wp-job-order', 'security' ); // this comes from wp_localize_script() in hrm-jobs.php
//capability check to ensure use caps
if ( ! current_user_can( 'manage_options' ) ) {
wp_die( __( 'You do not have permission to access this page.' ) );
}
$order = explode( ',', $_POST['order'] );
$counter = 0;
foreach ( $order as $item_id ) {
$post = array(
'ID' => (int) $item_id,
'menu_order' => $counter,
);
wp_update_post( $post );
$counter ++;
}
wp_send_json_success('POST SAVED');
}
My Ajax Call
jQuery(document).ready(function($) {
sortList = $( 'ul#custom-type-list' ); //store
var animation = $ ( '#loading-animation' );
var pageTitle = $ ( 'div h2');
sortList.sortable({
update: function ( event, ui) {
animation.show();
$.ajax({
url: ajaxurl, // ajaxurl is defined by WordPress and points to /wp-admin/admin-ajax.php
type: 'POST',
async: true,
cache: false,
dataType: 'json',
data:{
action: 'save_sort', // Tell WordPress how to handle this ajax request
order: sortList.sortable( 'toArray' ).toString(), // Passes ID's of list items in 1,3,2 format
security: WP_JOB_LISTING.security
},
success: function( response ) {
animation.hide();
$('div.updated').remove();
if( true === response.success ) {
console.log(sortList.sortable( 'toArray' ));
pageTitle.after(
'<div id="messsage" class="updated"><p>' + WP_JOB_LISTING.success + '</p></div>'
);
} else {
$('div.error').remove();
pageTitle.after( '<div id="messsage" class="error"><p>' + WP_JOB_LISTING.failure + '</div>' );
}
},
error: function ( error ) {
$( 'div.error' ).remove();
animation.hide();
//pageTitle.after( '<div id="messsage" class="error"><p>' + WP_JOB_LISTING.failure + '</div>' );
}
});
}//update
}); //sortable
});//jquery