On the checkout page in Woocommerce there is an "I accept terms and conditions" checkbox. The "terms and conditions" is a link, but Woocommerce captures the click event on the link, and instead opens a small popup(?) with the Terms and conditions page.
I would like to disable the script, and have it be just a normal link.
I identified the js code which captures this event. Unfortunately it's a part of checkout.min.js which controls other parts of the checkout experience too, so I would like to keep the rest of the script intact.
i = {
init: function() {
e(document.body).on("click", "a.woocommerce-terms-and-conditions-link", this.toggle_terms)
},
toggle_terms: function() {
if (e(".woocommerce-terms-and-conditions").length)
return e(".woocommerce-terms-and-conditions").slideToggle(), !1
}
};
i.init()
Bonus question, can I change the link to point to an arbitrary url (a pdf in this case)?
cale_b is right.
But because the link already has target="_blank" there is no need for add a new click handler. To archieve that your custom javascript code is load / run after WooCommerce's script you can use wp_add_inline_script.
I use this snippet and it works:
function disable_wc_terms_toggle() {
wp_add_inline_script( 'wc-checkout', "jQuery( document ).ready( function() { jQuery( document.body ).off( 'click', 'a.woocommerce-terms-and-conditions-link' ); } );" );
}
add_action( 'wp_enqueue_scripts', 'disable_wc_terms_toggle', 1000 );
Add this to your theme's functions.php and your done.
You can also do this by removing the woocommerce 'action'. Add this code to your functions.php file:
function stknat01_woocommerce_checkout_t_c_link() {
remove_action( 'woocommerce_checkout_terms_and_conditions', 'wc_terms_and_conditions_page_content', 30 );
}
add_action( 'wp', 'stknat01_woocommerce_checkout_t_c_link' )
WooCommerce uses jQuery, so you can use jQuery's off API to remove the event binding, and then assign your own event listener.
Important: The key to making this work is that your script MUST load / run after WooCommerce's script, otherwise the event won't be there to turn "off". If Woo's script runs after yours, it'll bind the event and yours won't remove it. I've demonstrated one method below, but you might need to use others (such as using a setTimeout):
// no-conflict-safe document ready shorthand
jQuery(function($) {
// wait until everything completely loaded all assets
$(window).on('load', (function() {
// remove the click event, and add your own to redirect
$( document.body )
.off( 'click', 'a.woocommerce-terms-and-conditions-link' )
.on( 'click', location.href='your_full_url_here');
});
});
Next, I anticipate you asking how to open the PDF in a new tab - for answers to that, see this question.
I followed this instructions for the removing inline toggle display of "Terms and conditions". It does not work until following code it is removed from checkout.min.js.
.slideToggle(),!1}},i={init:function(){e(document.body).on("click","a.woocommerce-terms-and-conditions-link",this.toggle_terms)},toggle_terms:function(){if(e(".woocommerce-terms-and-conditions").length)return e(".woocommerce-terms-and-conditions").slideToggle(),!1}};
After removing this line from checkout.min.js my checkout.js is also changed, here it is:
//remove toggle
/*
var wc_terms_toggle = {
init: function() {
$( document.body ).on( 'click', 'a.woocommerce-terms-and-conditions-link', this.toggle_terms );
},
toggle_terms: function() {
if ( $( '.woocommerce-terms-and-conditions' ).length ) {
$( '.woocommerce-terms-and-conditions' ).slideToggle();
return false;
}
}
};
*/
// no-conflict-safe document ready shorthand
jQuery(function($) {
// wait until everything completely loaded all assets
$(window).on('load', (function() {
// remove the click event, and add your own to redirect
$( document.body )
.off( 'click', 'a.woocommerce-terms-and-conditions-link' );
.on( 'click', location.href='https://yoursite.whatever');
});
});
wc_checkout_form.init();
wc_checkout_coupons.init();
wc_checkout_login_form.init();
//wc_terms_toggle.init();
});
Thank you for the script.
Related
I have the following code that triggers whenever the cart is updated.
The problem is that the jQuery version works as expected but the Vanilla JS doesn't.
jQuery( document.body ).on('updated_cart_totals', function( event ) {
console.log( 'in here' ); // Works.
} );
document.body.addEventListener( 'updated_cart_totals', function( event ) {
console.log( 'in here too' ); // Doesn't work.
} );
Is there something I am missing?
It appears to be answered before
https://stackoverflow.com/a/41727891/5454218
jQuery uses its own system of event/data binding which inter-operates only one way. In WooCommerce context it's an essential part of its system, so don't shy away from it. No shame in using jQuery when you're already deep in this pile of s**t.
My Answer would be, Yes it's now possible to detect by addAction() and doAction() using Vanilla JS -
wp.hooks.addAction().
wp.hooks.doAction()
How to do - My Approach
// Trigger any jQuery event
$document.trigger( 'test-trigger', [data] );
// Fire action
wp.hooks.doAction( 'test.trigger', data );
// Catch this event from anywhere in JS
wp.hooks.addAction( 'test.trigger', 'cp/test-trigger', function(data) {
console.log('JS Response data', data);
} , 10);
Reference Example of WordPress Core
For reference, Let's see a WordPress heartbeat js's doAction() - https://github.com/WordPress/wordpress-develop/blob/trunk/src/js/_enqueues/wp/heartbeat.js#L460
// heartbeat.js#L460
$document.trigger( 'heartbeat-tick', [response, textStatus, jqXHR] );
wp.hooks.doAction( 'heartbeat.tick', response, textStatus, jqXHR );
// Catch that heartbeat tick from anywhere in JS
wp.hooks.addAction( 'heartbeat.tick', 'cp/heartbeat-tick', function(response, textStatus, jqXHR) {
console.log('heartbeat response', response);
} , 10, 3);
Adding some jQuery to the WooCommerce checkout page that will hide/show a div based on shipping method (local pickup).
This works initially but due to WooCommerce's ajax loader when switching shipping method the hidden div fades back in when the change has occurred.
I am not sure how to trigger the code again once the switch has happened.
jQuery('form.checkout').on('change','select[name^="shipping_method"]',function() {
var val = jQuery( this ).val();
if (val.match("^local_pickup")) {
jQuery('.flexible-checkout-fields-review_order_before_submit').fadeIn();
} else {
jQuery('.flexible-checkout-fields-review_order_before_submit').fadeOut();
}
});
I expect the div (.flexible-checkout-fields-review_order_before_submit) to only be visible when local pickup is selected, else hide.
Like I say, it works initially, but when you switch the shipping method we are back to square one.
Any thoughts?
I think the issue might be in your first line where you have select[name instead of input[name
Here's some code I use for the same thing so should work for you if you change the name of the element you wish to hide.
I also check and uncheck the ship-to-different-address-checkbox depending on shipping method is selected.
And finally if shipping is required I scroll the page up to the shipping address.
Remove these features if you don't want them.
// When shipping method is selected
jQuery( 'form.checkout' ).on( 'change', 'input[name^="shipping_method"]', function () {
var val = jQuery( this ).val();
if ( val.match( "^local_pickup" ) ) {
jQuery( '#ship-to-different-address-checkbox' ).prop( "checked", false ); // untick shipping checkbox
jQuery( '.shipping_address' ).slideUp(); // hide shipping address
} else {
jQuery( '.shipping_address' ).slideDown(); // show shipping address
jQuery( '#ship-to-different-address-checkbox' ).prop( "checked", true ); // tick shipping checkbox
// scroll to top of shipping address
jQuery('html, body').animate({
scrollTop: jQuery(".shipping_address").offset().top - 120
}, 1500);
}
} );
In a plugin, we're using a button & text input to trigger the wpLink modal. All works well, until we hit a template that removes the main content editor and relies only on metaboxes for the page content.
The error we're getting is this.textarea is undefined. The code we're using is:
$( 'body' ).on( 'click', '.pluginxyz-add-link', function( event ) {
wpActiveEditor = true;
wpLink.open();
return false;
});
So I assume there is some dependency to the main editor. I can't find explicit info/documentation around this.. anyone have a suggestion about making this work without the main editor?
Actually, I just figured this out. In our code, the ONLY sibling text input is always where the value will go.
$( 'body' ).on( 'click', '.pluginxyz-add-link', function( event ) {
clickedEle = $( this );
textBoxID = $( clickedEle ).siblings( 'input[type=text]' ).attr( 'id' );
wpActiveEditor = true;
wpLink.open( textBoxID);
return false;
});
I have a header.php, that appears in every single page on my blog, with a navbar that looks like this:
<nav>
<ul>
<li>Logistics</li>
<li>Contact</li>
</ul>
</nav>
But when I click the anchor tag linking to #contact, which is located in page with id 5, as you can see by the php code, nothing happens. I tried using a slash (/#contact) but I keep getting the same behavior. Isn't this the correct way of linking to a specific id on another page?
EDIT: I also have some smooth scrolling code (below) which I think may be related to my issue.
<script>
$( document ).ready( function () {
// Add smooth scrolling to all links
$( "a" ).on( 'click', function ( event ) {
// Make sure this.hash has a value before overriding default behavior
if ( this.hash !== "" ) {
// Prevent default anchor click behavior
event.preventDefault();
// Store hash
var hash = this.hash;
// Using jQuery's animate() method to add smooth page scroll
// The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area
$( 'html, body' ).animate( {
scrollTop: $( hash ).offset().top
}, 800, function () {
// Add hash (#) to URL when done scrolling (default click behavior)
window.location.hash = hash;
} );
} // End if
} );
} );
</script>
Thanks!
You have a javascript error.
<script>
$( document ).ready( function () {
// Add smooth scrolling to all links
$( "a" ).on( 'click', function ( event ) {
// Make sure this.hash has a value before overriding default behavior
if ( this.hash !== "" ) {
// Prevent default anchor click behavior
event.preventDefault();
// Store hash
var hash = this.hash;
// Using jQuery's animate() method to add smooth page scroll
// The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area
$( 'html, body' ).animate( {
scrollTop: $( hash ).offset().top
}, 800, function () {
// Add hash (#) to URL when done scrolling (default click behavior)
window.location.hash = hash;
} );
} // End if
} );
} );
</script>
Here is the problem. On the home page you have a div with id #contato. On the other pages it is not there.
$( 'html, body' ).animate( {
scrollTop: $( hash ).offset().top
}, 800, function () {
// Add hash (#) to URL when done scrolling (default click behavior)
window.location.hash = hash;
} );
Your hash var's value is "#contato", but when js tries to get it's offset you recieve an error saying that it's impossible to read property top of 'undefined'. So, you can try to remove that part of the script from the other pages and only keep it on home. This should work like a charm. If you have any question, please ask.
LE: I'd recommend this method for smooth scroll (I didn't tested it for your case, but it always worked for me)
$(function() {
$('a[href*="#"]:not([href="#"])').click(function() {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
if (target.length) {
$('html, body').animate({
scrollTop: target.offset().top
}, 1000);
return false;
}
}
});
});
use
<?php echo get_page_link(5)."#contact"; ?>
instead of get permalink function
I know there is at least 1 other post on SO dealing with this but the answer was never exactly laid out.
I am working in a WP child theme in the head.php document. I have added this in the head:
<link type="text/css" href="http://www.frontporchdeals.com/wordpress/wp-includes/js/jqueryui/css/ui-lightness/jquery-ui-1.8.12.custom.css" rel="Stylesheet" />
<?php
wp_enqueue_style('template-style',get_bloginfo('stylesheet_url'),'',version_cache(),'screen');
wp_enqueue_script('jquery-template',get_bloginfo('template_directory').'/js/jquery.template.js',array('jquery'),version_cache(), true);
wp_enqueue_style('jquery-style', 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/themes/smoothness/jquery-ui.css');
wp_enqueue_script('jq-ui', 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.2/jquery-ui.js ');
wp_enqueue_script('jq-ui-min', 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.12/jquery-ui.min.js' );
?>
and I added this in the body:
<script>
jQuery(function() {
$( "#dialog" ).dialog();
});
</script>
<div id="dialog" title="Basic dialog">
<p>This is the default dialog which is useful for displaying information. The dialog window can be moved, resized and closed with the 'x' icon.</p>
</div>
but no dice. My div shows as standard div.
Any ideas at all? I know that top stylesheet should be called with enqueue but that shouldn't stop this from working.
WordPress jQuery is called in no-conflict mode:
jQuery(document).ready(function($) {
$('#dialog' ).dialog();
});
Also jQuery UI is loading before jQuery. You're getting 2 javascript errors:
Uncaught ReferenceError: jQuery is not defined
103Uncaught TypeError: Property '$' of object [object DOMWindow] is not a function
The first error is from jQuery UI loading before jQuery and the second is because the $ is not recognized in no-conflict mode.
Remove any of the inline <script src= tags and the call to the custom.css in header php and add this function to your child theme functions.php file to load the scripts. WordPress will put them in the right order for you.
add_action( 'init', 'frontporch_enqueue_scripts' );
function frontporch_enqueue_scripts() {
if (!is_admin() ) {
wp_enqueue_script( 'jquery' );
wp_register_script( 'google-jquery-ui', 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.12/jquery-ui.min.js', array( 'jquery' ) );
wp_register_script( 'jquery-template', get_bloginfo('template_directory').'/js/jquery.template.js',array('jquery'),version_cache(), true);
wp_register_style( 'jquery-style', 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/themes/smoothness/jquery-ui.css', true);
wp_register_style( 'template-style', 'http://www.frontporchdeals.com/wordpress/wp-includes/js/jqueryui/css/ui-lightness/jquery-ui-1.8.12.custom.css', true);
wp_enqueue_style( 'jquery-style' );
wp_enqueue_style( ' jquery-template' );
wp_enqueue_script( 'google-jquery-ui' );
wp_enqueue_script( 'jquery-template' );
}
}
I'm building a custom plugin on WP admin to insert data on custom MySQL tables. For nearly a week I was trying to do a confirmation dialog for a delete item event on a Wordpress table. After I almost lost all my hair searching for an answer, it seemed too good and simple to be true. But worked. Follows the code.
EDIT: turns out that the wp standard jquery wasn't working properly, and the Google hosted jQuery included in another class was making the correct calls for the JS. When I removed the unregister/register added below, ALL the other dialog calls stopped working. I don't know why this happened, or the jQuery version included in this particular WP distribution, but when I returned to the old registrations, using Google hosted scripts as seen below, everything went back to normality.
On PHP (first, register and call the script):
add_action('admin_init', 'init_scripts_2');
function init_scripts_2(){
///deregister the WP included jQuery and style for the dialog and add the libs from Google
wp_deregister_script('jquery-ui');
wp_register_script('jquery-ui', 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.2/jquery-ui.min.js');
wp_deregister_style('jquery-ui-pepper-grinder');
wp_register_style('jquery-ui-pepper-grinder', 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.2/themes/pepper-grinder/jquery-ui.min.css');
wp_enqueue_script('jquery-ui'); ///call the recently added jquery
wp_enqueue_style('jquery-ui-pepper-grinder'); ///call the recently added style
wp_deregister_script('prevent_delete'); ///needed the deregister. why? don't know, but worked
///register again, localize and enqueue your script
wp_register_script('prevent_delete', WP_PLUGIN_URL . '/custom_plugin/js/prevent_delete.js', array('jquery-ui'));
wp_localize_script('prevent_delete', 'ajaxdelete', array('ajaxurl' => admin_url('admin-ajax.php')));
wp_enqueue_script('prevent_delete');
}
Next, if you're opening the dialog on a click event, like me, make sure you ALWAYS use class instead of id to identify the button or link later, on jQuery.
<a class="delete" href="?page=your_plugin&action=delete">Delete</a>
We also need to use a tag that holds the dialog text. I needed to set the style to hide the div.
<div id="dialog_id" style="display: none;">
Are you sure about this?
</div>
Finally, the jQuery.
/*jslint browser: true*/
/*global $, jQuery, alert*/
jQuery(document).ready(function ($) {
"use strict";
///on class click
$(".delete").click(function (e) {
e.preventDefault(); ///first, prevent the action
var targetUrl = $(this).attr("href"); ///the original delete call
///construct the dialog
$("#dialog_id").dialog({
autoOpen: false,
title: 'Confirmation',
modal: true,
buttons: {
"OK" : function () {
///if the user confirms, proceed with the original action
window.location.href = targetUrl;
},
"Cancel" : function () {
///otherwise, just close the dialog; the delete event was already interrupted
$(this).dialog("close");
}
}
});
///open the dialog window
$("#dialog_id").dialog("open");
});
});
EDIT: The call for the standard wp dialog style didn't work after all. The "pepper-grinder" style made the dialog appear correctly in the center of the window. I know the looks for the dialog are not very easy on the eye, but i needed the confirmation dialog and this worked just fine for me.
The dialog div is created AFTER when you're trying to act upon it. Instead, you should use:
$(document).ready(function() {
$( "#dialog" ).dialog();
});