Tracking in Woocommerce - woocommerce

Hello brilliant people.
i have a problem here with tracking on the cart page. I need to send data to my third party crm.
it is an addtobasket event, but it needs to run on the basket page and send all the basket items.
i have tried with this, but it sends the same 1 productid everytime instead of looping through it:
add_action('wp_footer', 'zz_add_tracking_codes3');
function zz_add_tracking_codes3(){
// adding on product page only
if(Is_cart){
global $woocommerce;
$items = $woocommerce->cart->get_cart();
foreach($items as $item => $values){
$produc_id = get_the_id();
$categories = get_the_terms( $produc_id, 'product_cat');
?>
<script type="text/javascript" language="javascript">
const PRODUCTID = '<?php echo $produc_id; ?>';
const CATEGORYID = '<?php echo $categories[0]->term_id; ?>';
const CATEGORYNAME = '<?php echo $categories[0]->name; ?>';
var hlt;
var BiTrackingLoaded = function (BiTracking) {
hlt=BiTracking;
BiTracking.initialize('c5gizkvDg3PurFHH', 1, '7468');
hlt.addToBasket(PRODUCTID, PRODUCT COUNT, CATEGORYID, BASKETID, CATEGORYNAME); }
</script>
<script>
(function (d, t) {
var g = d.createElement(t),
s = d.getElementsByTagName(t)[0];
h = "https:" == document.location.protocol ? "https://" : "http://";
g.src = h + 'tracking.heycommerce.dk/hlbi.js';
s.parentNode.insertBefore(g, s);
}
(document, 'script'));
</script>
<?php
}}}
and in the console it says product id has already been declared when adding more items.
You can check by going to frkfaerch.dk
EDIT: it actually also doesnt correctly get the id of the product, it seems to be getting the pageid.
/*Produkt side tracking*/
add_action('wp_footer', 'zz_add_tracking_codes');
function zz_add_tracking_codes(){
// adding on product page only
if(is_singular( 'product' )){
$produc_id = get_the_id();
$categories = get_the_terms( $produc_id, 'product_cat');
?>
<script type="text/javascript" language="javascript">
const PRODUCTID = '<?php echo $produc_id; ?>';
const CATEGORYID = '<?php echo $categories[0]->term_id; ?>';
const CATEGORYNAME = '<?php echo $categories[0]->name; ?>';
var hlt;
var BiTrackingLoaded = function (BiTracking) {
hlt=BiTracking;
BiTracking.initialize('c5gizkvDg3PurFHH', 1, '7468');
hlt.visit(PRODUCTID,CATEGORYID,CATEGORYNAME) }
</script>
<script>
(function (d, t) {
var g = d.createElement(t),
s = d.getElementsByTagName(t)[0];
h = "https:" == document.location.protocol ? "https://" : "http://";
g.src = h + 'tracking.heycommerce.dk/hlbi.js';
s.parentNode.insertBefore(g, s);
}
(document, 'script'));
</script>
<?php
}
}
This code is running in product pages and works, sending productid, categoryname and category id in the payload.

Related

How to get variation_id with AJAX when click add to cart Woocommerce?

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.

Isotope with wordpress filtering does not work

I check the other posts on this subject but I did not find the answer to my problem.
I follow this tutorial : https://www.aliciaramirez.com/2014/03/integrating-isotope-with-wordpress/
But when I test and click on a filter, nothing happen... I return to the top of my website and that's it. Don't understand why
My js :
jQuery(function ($) {
var $container = $('#isotope-list'); //The ID for the list with all the blog posts
$container.isotope({ //Isotope options, 'item' matches the class in the PHP
itemSelector : '.item',
layoutMode : 'fitRows'
});
//Add the class selected to the item that is clicked, and remove from the others
var $optionSets = $('#filters'),
$optionLinks = $optionSets.find('a');
$optionLinks.click(function(){
var $this = $(this);
// don't proceed if already selected
if ( $this.hasClass('selected') ) {
return false;
}
var $optionSet = $this.parents('#filters');
$optionSets.find('.selected').removeClass('selected');
$this.addClass('selected');
//When an item is clicked, sort the items.
var selector = $(this).attr('data-filter');
$container.isotope({ filter: selector });
return false;
});
});
And my php :
<section>
<ul id="filters">
<li>Everything</li>
<?php
$terms = get_terms("category"); // get all categories, but you can use any taxonomy
$count = count($terms); //How many are they?
if ( $count > 0 ){ //If there are more than 0 terms
foreach ( $terms as $term ) { //for each term:
echo "<li><a href='#' data-filter='.".$term->slug."'>" . $term->name . "</a></li>\n";
//create a list item with the current term slug for sorting, and name for label
}
}
?>
</ul>
<?php $the_query = new WP_Query( 'posts_per_page=6' ); //Check the WP_Query docs to see how you can limit
// which posts to display ?>
<?php if ( $the_query->have_posts() ) : ?>
<div id="isotope-list">
<?php while ( $the_query->have_posts() ) : $the_query->the_post();
global $post;
$termsArray = get_the_terms( $post->ID, "category" ); //Get the terms for this particular item
$termsString = ""; //initialize the string that will contain the terms
foreach ( $termsArray as $term ) { // for each term
$termsString .= $term->slug.' '; //create a string that has all the slugs
}
?>
<div class="<?php echo $termsString; ?> item"> <?php // 'item' is used as an identifier ?>
<h3><?php the_title(); ?></h3>
</div> <!-- end item -->
<?php endwhile; ?>
</div> <!-- end isotope-list -->
<?php endif; ?>
</section>
thanks a lot for help
From the example i have provided to you - codepen.io/Igorxp5/pen/ojJLQE
This is single term filter so keep that in mind.
For multi term filter you can check this one -https://codepen.io/TimRizzo/details/ervrRq
First prepare your template and query
<section>
<ul class="filters">
<?php
$terms = get_terms("category");
if($terms):
echo '<li>All</li>';
foreach ( $terms as $term ):
echo '<li>'.$term->name.'</li>';
endforeach;
endif;
?>
</ul>
<?php
$the_query = new WP_Query( 'posts_per_page=-1' ); // We need all posts
if ( $the_query->have_posts() ) :
echo '<div id="container" class="isotope">';
while ( $the_query->have_posts() ) : $the_query->the_post();
$terms = get_the_terms( get_the_ID(),'category');
// Filter is working with single term so i am getting first from array or keep posts with single category/tag or w/e.
echo '<div class="grid-item" data-filter="'.$terms[0]->slug.'">'.get_the_title().'</div>';
endwhile;
endif;
?>
</section>
From there in your js file add the following
jQuery(function ($) {
$(document).ready( function() {
var itemSelector = '.grid-item'; // Item class change if needed
var $container = $('#container').isotope({ // change ID of container if needed
itemSelector: itemSelector,
masonry: {
columnWidth: itemSelector,
isFitWidth: true
}
});
// Responsive pagination
var responsiveIsotope = [
[480, 2], // Bellow 480px wide 2 items per page
[720, 4] //Below 720px wide 4 items per page
];
var itemsPerPageDefault = 6; // Items per page unless responsiveIsotope . Over 720px wide 6 items per page
var itemsPerPage = defineItemsPerPage();
var currentNumberPages = 1;
var currentPage = 1;
var currentFilter = '*';
var filterAtribute = 'data-filter'; //Used for the filter
var pageAtribute = 'data-page'; // Used for the pagination
var pagerClass = 'isotope-pager'; // Class of the pagination container
function changeFilter(selector) {
$container.isotope({
filter: selector
});
}
function goToPage(n) {
currentPage = n;
var selector = itemSelector;
selector += ( currentFilter != '*' ) ? '['+filterAtribute+'="'+currentFilter+'"]' : '';
selector += '['+pageAtribute+'="'+currentPage+'"]';
changeFilter(selector);
}
function defineItemsPerPage() {
var pages = itemsPerPageDefault;
for( var i = 0; i < responsiveIsotope.length; i++ ) {
if( $(window).width() <= responsiveIsotope[i][0] ) {
pages = responsiveIsotope[i][1];
break;
}
}
return pages;
}
function setPagination() {
var SettingsPagesOnItems = function(){
var itemsLength = $container.children(itemSelector).length;
var pages = Math.ceil(itemsLength / itemsPerPage);
var item = 1;
var page = 1;
var selector = itemSelector;
selector += ( currentFilter != '*' ) ? '['+filterAtribute+'="'+currentFilter+'"]' : '';
$container.children(selector).each(function(){
if( item > itemsPerPage ) {
page++;
item = 1;
}
$(this).attr(pageAtribute, page);
item++;
});
currentNumberPages = page;
}();
var CreatePagers = function() {
var $isotopePager = ( $('.'+pagerClass).length == 0 ) ? $('<div class="'+pagerClass+'"></div>') : $('.'+pagerClass);
$isotopePager.html('');
for( var i = 0; i < currentNumberPages; i++ ) {
var $pager = $('');
$pager.html(i+1);
$pager.click(function(){
var page = $(this).eq(0).attr(pageAtribute);
goToPage(page);
});
$pager.appendTo($isotopePager);
}
$container.after($isotopePager);
}();
}
setPagination();
goToPage(1);
//When we click a filter grab value ,recalculate pagination, reset pagination
$('.filters a').click(function(){
var filter = $(this).attr(filterAtribute);
currentFilter = filter;
setPagination();
goToPage(1);
});
// On resize triger responsive pagination
$(window).resize(function(){
itemsPerPage = defineItemsPerPage();
setPagination();
goToPage(1);
});
});
});

Google Maps API V3 errors after upgrading a WP plugin

After upgrading WP Advanced Custom Fields , I'm having problem with google maps . Map is showing correctly but page is loadin endlessely .
JS error console in FF showing errors :
Error: a is undefined
Source File: https://maps.gstatic.com/intl/en_us/mapfiles/api-3/10/19/main.js
Line: 70
Error: q.queue[Za]() is not a function
Source File: https://maps.gstatic.com/intl/en_us/mapfiles/api-3/10/19/main.js
Line: 74
my code which is generating map JS is :
<script type="text/javascript" src="https://maps.google.com/maps/api/js? key=AIzaSyCwynu3lxKxNPk5DNMWCx8oyGX8ka8_KqU&sensor=false"></script>
<script type="text/javascript">
//<![CDATA[
var is_init = false;
var map;
function map_init() {
var latlng = new google.maps.LatLng(<?php echo $lat; ?>, <?php echo $lng; ? >);
var myOptions = {
zoom: <?php echo $zoom; ?>,
center: latlng,
scrollwheel: false,
panControl: false,
zoomControl: true,
mapTypeControl: false,
scaleControl: true,
streetViewControl: true,
overviewMapControl: false,
mapTypeId: google.maps.MapTypeId.<?php echo $maptype; ?>
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOp tions);
var marker;
var latlng;
<?php $i = 0; foreach($markers as $title=>$marker): ?>
<?php if(!empty($marker['lat']) && !empty($marker['lng'])) { ?>
latlng = new google.maps.LatLng(<?php echo $marker['lat']; ?>,<?php echo $marker['lng']; ?>);
marker<?php echo $i; ?> = new google.maps.Marker({
position: latlng,
map: map,
icon: '/wp-content/themes/iw/marker/<?php echo $marker['typ']; ? >.png',
title: '<?php echo $title; ?>'
});
google.maps.event.addListener(marker<?php echo $i; ?>, 'click', function() {
window.location.href = '<?php echo $marker['link']; ?>';
});
google.maps.event.addListener(marker<?php echo $i; ?>, 'mouseover', function() {
jQuery('.sbmlink<?php echo $i; ?>').addClass('mouseover');
});
google.maps.event.addListener(marker<?php echo $i; ?>, 'mouseout', func tion() {
jQuery('.sbmlink<?php echo $i; ?>').removeClass('mouseover');
});
<?php } ?>
<?php $i++; endforeach; ?>
is_init = true;
}
jQuery(function(){
jQuery('#map_button').click(function(){
jQuery('#map_canvas').toggle();
if (!is_init) {
map_init();
}
if(jQuery('#map_button').html() == 'Hier klicken, um die Karte einzublenden') {
jQuery('#map_button').html('Hier klicken, um die Karte auszublenden');
document.cookie="mapstate=open; path=/;";
} else {
jQuery('#map_button').html('Hier klicken, um die Karte einzublenden');
document.cookie="mapstate=closed; path=/;";
}
});
<?php if ($mapstate == 'open' || ($map_default_open && !isset($_COOKIE['mapstate']))): ?>
jQuery('#map_button').click();
<?php endif; ?>
jQuery.ajax({
dataType : 'json',
// url : '/wetter.php?ort=<?php echo $custom['wetterort'][0]; ?>',
success : function(data) {
jQuery('.wetterzustand').html(data.wetterzustand);
jQuery('.wettertemperatur').html(data.wettertemperatur + ' °C');
jQuery('.wettericon').html('<img alt="' + data.wetterzustand + '" src="' + data.wettericon + '"/>');
}
});
});
//]]>
</script>
these error came because when we update wordpress,it doesnot update jquery-ui,
so we need to insert code manually in the functions.php of our theme to update jquery-ui as well.
I was also facing the same problem.It helped me.
function new_google_map_script($post) {
wp_enqueue_style('admin-main', get_bloginfo('template_url') . '/css/admin-main.css');
//wp_enqueue_style('jquery-ui', get_bloginfo('template_url') . '/css/jquery-ui.css');
wp_enqueue_style('wp-jquery-ui');
wp_enqueue_style('wp-jquery-ui-dialog');
}
add_action('wp_enqueue_scripts', 'new_google_map_script');

Full Calendar not displaying my events from my database

The events from my database are not displayed on my Full Calendar. I used the codes from the examples that I've seen online so please bear with the codes that I have right now. I would appreciate all the help that I will get from you guys. Thanks!
<script>
$(document).ready(function() {
// page is now ready, initialize the calendar...
$('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},editable: false,
events: "json_events.php",
eventDrop: function(event, delta) {
alert(event.title + ' was moved ' + delta + ' days\n' +
'(should probably update your database)');
},
loading: function(bool) {
if (bool) $('#loading').show();
else $('#loading').hide();
}
});
});
</script>
json_events.php
<?php
include 'connect.php';
session_start();
$result = mysql_query("SELECT ID, title, startDate AS startDate FROM events");
mysql_close();
$events = array();
while ($row=mysql_fetch_array($result)){
$title = $row['title'];
$eventsArray['id'] = $row['ID'];
$eventsArray['title'] = $title;
$eventsArray['startDate'] = $row['startDate'];
$events[] = $eventsArray;
}
echo json_encode($events);
?>
<?php
include 'connect.php';
session_start();
$result = mysql_query("SELECT ID, title, startDate AS startDate FROM events");
mysql_close();
$events = array();
while ($row=mysql_fetch_array($result)){
$id = $row['ID'];
$title = $row['title'];
$start = $row['startDate'];
$events = array(
'id' => "$id",
'title' => "$title",
'start' => "$start"
);
}
echo json_encode($events);
?>
That should work for you. If you do not want the even to be all day just add 'allDay' => "" after the start statement.

index content disappears in Wordpress

I'm making a plugin, and this function includes map at the end of the single post.
Problem is, content disappears on index. Can you tell me how should I recode this function so it wouldnt affect content on index?
function svmpm_display_svm( $content ) {
global $post, $options;
$options = get_option('svmpm_options');
$metaname = $options['metaname'];
$sheight = $options['hght'];
$swidth = $options['wdth'];
$svmpmaddress = get_post_meta($post->ID, $metaname, true);
if(is_single()) {
$acontent = '<div onunload="GUnload()">
<script src="http://maps.google.com/maps?file=api&v=2&sensor=false" type="text/javascript"></script>
<div id="map_canvas" style="width: ';
$acontent .= $swidth;
$acontent .= '; height: ';
$acontent .= $sheight;
$acontent .= '"></div>
<script type="text/javascript">
var myAddress = ';
$acontent .= '\'';
$acontent .= $svmpmaddress;
$acontent .= '\';';
$acontent .= 'var userLocation = myAddress;
if (GBrowserIsCompatible()) {
var geocoder = new GClientGeocoder();
geocoder.getLocations(userLocation, function (locations) {
if (locations.Placemark)
{
var north = locations.Placemark[0].ExtendedData.LatLonBox.north;
var south = locations.Placemark[0].ExtendedData.LatLonBox.south;
var east = locations.Placemark[0].ExtendedData.LatLonBox.east;
var west = locations.Placemark[0].ExtendedData.LatLonBox.west;
var bounds = new GLatLngBounds(new GLatLng(south, west),
new GLatLng(north, east));
new GStreetviewPanorama(document.getElementById("map_canvas"),
{ latlng: bounds.getCenter() });
}
});
}
</script>
</div>';
if ($options['pbelow'] == 1) { //Only below p
return $content . $acontent;
};
} ;
};
add_filter('the_content', 'svmpm_display_svm');
Try putting
if (! is_single()) return $content;
at the top of your function. It doesn't look like you ever return the $content outside of your if (is_single()) block.

Resources