Embed clickwork7 tracking code with the transaction ID in Woocommerce - javascript

In Woocommerce, I was looking to get order ID just before payment, when the order is created. I found this answer below:
Get the order ID in checkout page before payment process
What I need is to pass in tracking script the transaction ID (as specified on the script) and I should be able to track in clickwork7 dashboard:
<script type="text/javascript" src="https://clickwork7secure.com/p.ashx?
o=45875&e=12995&f=js&t=TRANSACTION_ID"></script>
But the transaction ID seems to be empty after a purchase in Paypal for example, so may be I should pass the order ID instead.
The Order received page seems to be the right place, but for cancelled or failed orders, Where and how to embed this script?
Any help is appreciated.

Updated: It is possible to use many different hooks for that:
wp_head
wp_footer
woocommerce_thankyou
You can try to use the:
Order id (Is easy to get it)
Order Key: $order_key = get_post_meta( $order_id, '_order_key', true );
Transaction id: $transaction_id = get_post_meta( $order_id, '_transaction_id', true );
1) Using woocommerce_thankyou hook: The simpler way as the Order Id is a hook argument:
add_action( 'woocommerce_thankyou', 'checkout_clickwork_js_script', 22, 1 );
function checkout_clickwork_js_script( $order_id ) {
if ( ! $order_id ) return; // Exit
$transaction_id = get_post_meta( $order_id, '_transaction_id', true );
$order_key = get_post_meta( $order_id, '_order_key', true );
if( ! empty($transaction_id) ){
$value = $transaction_id; // TRANSACTION ID
}
elseif( ! empty($order_key) ){
$value = $transaction_id; // ORDER KEY
}
else {
$value = $transaction_id; // ORDER ID
$url = "https://clickwork7secure.com/p.ashx?o=45875&e=12995&f=js&t=$value";
?><script type="text/javascript" src="<?php echo $url; ?>"></script> <?php
}
Code goes in function.php file of your active child theme (or active theme). It should work.
2) Using wp_head hook:
add_action( 'wp_head', 'checkout_clickwork_js_script', 998 );
function checkout_clickwork_js_script() {
// Only order-received page
if( is_wc_endpoint_url('order-received') ) :
global $wp;
$order_id = absint( $wp->query_vars['order-received'] );
if ( ! $order_id || empty($order_id) )
return; // Exit
$transaction_id = get_post_meta( $order_id, '_transaction_id', true );
$order_key = get_post_meta( $order_id, '_order_key', true );
if( ! empty($transaction_id) ){
$value = $transaction_id; // TRANSACTION ID
}
elseif( ! empty($order_key) ){
$value = $transaction_id; // ORDER KEY
}
else {
$value = $transaction_id; // ORDER ID
$url = "https://clickwork7secure.com/p.ashx?o=45875&e=12995&f=js&t=$value";
?><script type="text/javascript" src="<?php echo $url; ?>"></script> <?php
endif;
}
Code goes in function.php file of your active child theme (or active theme). It should work.
The condition if( is_wc_endpoint_url('order-received') ) : can be extended to handle cancelled and failed orders custom endpoints too …
Similar answers:
Add Order data in Adword Conversion Code in Woocommerce
Linkwise Affiliate integration in Woocommerce thankyou page

Related

get posts using taxonomy in wordpress

I have a wordpress app locally setup in my computer. In the wordpress admin i have a Countries tab under the Posts. I'll attach an image for better understanding.
I want to write a function to get the country values for my front-end. For that i have written a function like this
public function get_destinations()
{
$bookings = get_posts(
array(
'taxonomy'=> 'country',
'numberposts' => -1,
)
);
return $bookings;
}
But for some reason this function returns all the posts in the database. I want to get only the country names.
i found the taxonomy from my local url which is
http://localhost/my_project/wp-admin/edit-tags.php?taxonomy=country
I'm very new to wordpress and dont have a clue on how to retrieve these data to my front end. What am i doing wrong here?
If you want to show the only category or taxonomy name instead of get_posts you have to use get_terms
check this code.
// Get the taxonomy's terms
$terms = get_terms(
array(
'taxonomy' => 'country',
'hide_empty' => false, // show category even if dont have any post.
)
);
// Check if any term exists
if ( ! empty( $terms ) && is_array( $terms ) ) {
// Run a loop and print them all
foreach ( $terms as $term ) { ?>
<a href="<?php echo esc_url( get_term_link( $term ) ) ?>">
<?php echo $term->name; ?>
</a><?php
}
}

Improving upon a feature on a Wordpress site that changes phone number displayed to user in the header based on their IP address

My question is regarding suggestions for improvements of a feature I created on a Wordpress site that changes the phone number displayed to user in the header based on their IP address. The default is a 1-866 number to be displayed if area does not appear to be serviced etc.
In my functions.php file I created the below functions to use ipinfo.io to find the city of the user, compare it to the field of city I created to be associated with each location post and then if there is a match the second function returns the phone number field associated with that location. See functions below:
//Returns users city based on IP address
function get_the_user_ip() {
if ( ! empty( $_SERVER['HTTP_CLIENT_IP'] ) ) {
//Checks if IP is from shared internet
$ip = $_SERVER['HTTP_CLIENT_IP'];
}
elseif ( ! empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) {
//Checks if IP is passed from proxy
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
}
else {
//Most trustworthy source of IP address
$ip = $_SERVER['REMOTE_ADDR'];
}
//$ip='104.238.96.194'; //--used this to test different IP addresses--
//Uses ipinfo.io to find location information based on IP address
$details = json_decode(file_get_contents("https://ipinfo.io/{$ip}"));
//Returns city value from the details array
$city=$details->city;
return apply_filters('wpb_get_ip', $city );
}
//Returns correct phone number based on a user's location
function zip_display(){
$args = array(
'posts_per_page' => -1,
'post_type' => 'Locations',
'post_status' => ('publish')
);
$wp_query = new WP_Query($args);
//var_dump($wp_query);
if( $wp_query->have_posts() ): while( $wp_query->have_posts() ) : $wp_query->the_post();
$userCity=get_the_user_ip();
$stateField=get_field('state');
$cityField=get_field('city');
$phoneField=get_field('phone_number');
if($userCity==$cityField){
return ( '<span class="phone-span">' . $phoneField . '</span>');
}
endwhile;
wp_reset_postdata();
endif;
}
To display the correct phone number in the header I inserted a <div> element with the id of phone directly into an auxiliary header like so:
Then to target this div id I inserted the below JavaScript directly into my footer.php
<script>document.getElementById("phone").innerHTML = '<?php echo zip_display(); ?>';</script>
Is this an acceptable way to go about doing this? Everything is working correctly more or less right now. The only issue I am having so far is it seems for at least one person neither the default 1-866 number is being displayed to them nor a specific number based on their location? Does anyone have any ideas why that would be? Does it possibly have to do with a browser setting that does not allow JavaScript scripts to be shown in the way I constructed it?
The zip_display() function in your posted code will only return a span element if the $userCity matches the $cityField. You need to return the span containing the default phone number if the cities do not match. Change your condition to something like this:
if($userCity==$cityField){
return ( '<span class="phone-span">' . $phoneField . '</span>');
}else{
return ( '<span class="phone-span">' . $defaultPhoneNumber . '</span>');
}
In order to improve the functionality of this feature I did the following:
In my get_the_user_ip function I decided to use the free WordPress plugin GeoIP Detection, instead of ipinfo.io
See modification to get_the_user_ip function below:
`//Returns users city based on IP address`
function get_the_user_ip() {
if ( ! empty( $_SERVER['HTTP_CLIENT_IP'] ) ) {
//Checks if IP is from shared internet
$ip = $_SERVER['HTTP_CLIENT_IP'];
}
elseif ( ! empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) {
//Checks if IP is passed from proxy
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
}
else {
//Most trustworthy source of IP address
$ip = $_SERVER['REMOTE_ADDR'];
}
$record = geoip_detect2_get_info_from_ip($ip, NULL);
$city=$record->city->name;
return apply_filters('wpb_get_ip', $city );
}
In my zip_display function I added a return statement outside of while loop. In order to return a default phone number if the user's city cannot be matched to a location. This works better than an if/else statement because it will only execute once the loop has completed all iterations.
function zip_display(){
$args = array(
'posts_per_page' => -1,
'post_type' => 'Locations',
'post_status' => ('publish')
);
$wp_query = new WP_Query($args);
if( $wp_query->have_posts() ): while( $wp_query->have_posts() ) : $wp_query->the_post();
$userCity=get_the_user_ip();
$cityField=get_field('city');
$phoneField=get_field('phone_number');
if($userCity==$cityField){
return ('<a class="phone-span" href="tel:1-'. $phoneField . '">' . $phoneField . '</a>');
}
endwhile;
return('<a class="phone-span" href="tel:1-866-000-0000">1-866-000-0000</a>');
wp_reset_postdata();
endif;
}
Lastly I modified my footer.php file, separating my JavaScript script into a variable so that the script would not throw an Uncaught TypeErron: Cannot read property '....' of null.
<script>
var ipphone = '<?php echo zip_display(); ?>'
if(ipphone){document.getElementById("phone").innerHTML = ipphone;}
</script>

Adding javascript to php (wordpress)? [duplicate]

This question already has answers here:
How to get JavaScript variable value in PHP
(10 answers)
Closed 5 years ago.
So I am helping my friend with his woocommerce WordPress site. He has some short javascript code that needs to be added to the thank you page for the site.
The javascript code takes three variables (totalCost, orderId and setProductId). I can not get to the HTML. So how do I add this code to the PHP and also, how do I access the variables from the PHP and write them into the javascript?
And where in the already existing code should I add it? Is it in the functions.php file for the theme?
I would be super thankful for help!
EDIT:
So would this work?
add_action( 'studentkortet_tracking', 'my_custom_tracking' );
function studentkortet_tracking($order_id){
?>
<script id="pap_x2s6df8d" src="http://URL_TO_PostAffiliatePro/scripts/trackjs.js" type="text/javascript">
</script>
<script type="text/javascript">
PostAffTracker.setAccountId(’xxxxxx’);
var sale = PostAffTracker.createSale();
sale.setTotalCost('<?php echo ($order->order_total - $order->order_shipping); ?>');
sale.setOrderID('<?php echo $order->id; ?>');
sale.setCurrency('<?php echo $order->get_order_currency(); ?>');
PostAffTracker.register();
</script>
<?php
}
Here is some working code, answered here
<script>
var p1 = "success";
</script>
<?php
echo "<script>document.writeln(p1);</script>";
?>
Here's the correct way of accessing PHP variables within a script. It utilises the function wp_localize_script() so that PHP variables are accessible in a script file. First include this file in your functions.php file
function example_enqueue_scripts() {
if( is_checkout() ) {
$args = array( 'total_cost' => 443, 'order_id' => 4567, 'set_product_id' => 123 );
wp_register_script( 'checkout-script', get_stylesheet_directory_uri() . '/checkout-script.js' );
wp_localize_script( 'checkout-script', 'checkout_script', $args );
wp_enqueue_script( 'checkout-script' );
}
}
add_action( 'wp_enqueue_scripts', 'example_enqueue_scripts' );
Then include this javascript in a file under your theme folder called checkout-script.js for example.
(function( $ ) {
'use strict';
$(function() {
var totalCost = checkout_script.total_cost;
var orderId = checkout_script.order_id;
var setProductId = checkout_script.set_product_id;
exampleFunction( totalCost, orderId, setProductId );
function exampleFunction( totalCost, orderId, setProductId ) {
//Do something in here
//alert(totalCost);
}
});
})( jQuery );
I don't know what setProductId is meant to be as a variable, but the hook you are looking for is woocommerce_thankyou. The $order_id is passed by default, which you can then use to grab the order object. Pretty much all the info related to the order can be accessed through the setter/getter methods on the order object.
/**
* Print Javascript on Thankyou page.
* #param int $order_id
*/
function so_47117329_thankyou( $order_id ){
$order = wc_get_order( $order_id ); ?>
<script id="pap_x2s6df8d" src="http://URL_TO_PostAffiliatePro/scripts/trackjs.js" type="text/javascript">
</script>
<script type="text/javascript">
PostAffTracker.setAccountId(’xxxxxx’);
var sale = PostAffTracker.createSale();
sale.setTotalCost('<?php echo $order->get_total() - $order->get_shipping_
(); ?>');
sale.setOrderID('<?php echo $order_id; ?>');
sale.setCurrency('<?php echo $order->get_order_currency(); ?>');
PostAffTracker.register();
</script>
<?php
}
add_action( 'woocommerce_thankyou', 'so_47117329_thankyou' );
Editing to add an alternative for enqueuing the scripts as suggested by #Andrew-Schultz. Using the woocommerce_thankyou hook gets you easy access to the $order_id, which would otherwise need to be retrieved from the URL. You will still access the javascript variables as he's shown in his answer.
/**
* Enqueue Javascript on Thankyou page.
* #param int $order_id
*/
function so_47117329_thankyou( $order_id ){
$order = wc_get_order( $order_id );
$args = array(
'total_cost' => $order->get_total(),
'order_id' => $order_id,
'set_product_id' => 123
);
wp_register_script( 'checkout-script', get_stylesheet_directory_uri() . '/checkout-script.js', array(), false, true ); // Last parameter loads script in footer
wp_localize_script( 'checkout-script', 'checkout_script', $args );
wp_enqueue_script( 'checkout-script' );
}
add_action( 'woocommerce_thankyou', 'so_47117329_thankyou' );

Why ajax request isn't sending all the data?

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.

How to debug PHP script not executing?

I'm working on a wordpress page here http://beta.fray.it/invite and on clicking the Twitter icon I have this onclick attribute set on a list element
onclick="window.location.href = '<?php echo get_template_directory_uri(); ?>/components/invite/twitter/redirect.php';">
this takes me to the php file which should redirect users to Twitter for authentication. I got this working on another server I use for testing, but not here. What happens is that I see content from the main page http://beta.fray.it but no redirection. What is the reason for this?
After you enable WP_DEBUG and WP_DEBUG_LOG in wp-config.php (WP_DEBUG is disabled by default since WP_DEBUG is set to false).
debug.log is generated in your /wp-content/ directory upon an error, warning, a notice or a log call.
You can also utilize a wrapper function to centralize your log calls
if(!function_exists('_log')){
function _log( $message ) {
if( WP_DEBUG === true ){
if( is_array( $message ) || is_object( $message ) ){
error_log( print_r( $message, true ) );
} else {
error_log( $message );
}
}
}
}
you can read more about that here
Check out the codex as well:
http://codex.wordpress.org/Debugging_in_WordPress
try changing your link href
onclick='window.location.href =' + "<?php echo get_template_directory_uri(); ?>" + '/components/invite/twitter/redirect.php';

Categories

Resources