Trigger Js function onclick - javascript

I am using wordpress and have a function like this, how to redirect to the corresponding url only happens onclick, for now the "en" language page is automatically redirecting after the page load, but the "zh-hant" redirecting after click, anyone can help me to check the code?
Thanks.
add_action( 'wp_head', 'redirect_after_booking' );
function redirect_after_booking() {
if ( in_category('teachers') ) {
if(ICL_LANGUAGE_CODE=='en'){
?>
<script>
window.beforeConfirmedBooking = function() {
window.location.href = "https://aaa.com";
};
</script>
<?php
}
if(ICL_LANGUAGE_CODE=='zh-hant'){
?>
<script>
window.beforeConfirmedBooking = function() {
window.location.href = "https://aaa.com/zh-hant";
};
</script>
<?php
}
}
}

You should be doing all of it in one function itself
add_action( 'wp_head', 'redirect_after_booking' );
function redirect_after_booking() {
if ( in_category('teachers') ) {
$url_endpoint = '';
if(ICL_LANGUAGE_CODE=='en'){
} else if (ICL_LANGUAGE_CODE=='zh-hans') {
$url_endpoint = '/zh-hans';
}else if (ICL_LANGUAGE_CODE=='zh-hant') {
$url_endpoint = '/zh-hant';
}
?>
<script>
window.beforeConfirmedBooking = function() {
window.location.href = "https://aaa.com<?php echo $url_endpoint; ?>";
};
const btn = document.querySelector('.el-button .el-button--primary .redirect-link');
btn.addEventListener('click', beforeConfirmedBooking);
</script>
<?php
}
}
You can also do it just using php and no js at all
add_action( 'wp_head', 'redirect_after_booking' );
function redirect_after_booking() {
if ( in_category('teachers') ) {
$url_endpoint = '';
if(ICL_LANGUAGE_CODE=='en'){
} else if (ICL_LANGUAGE_CODE=='zh-hans') {
$url_endpoint = '/zh-hans';
}else if (ICL_LANGUAGE_CODE=='zh-hant') {
$url_endpoint = '/zh-hant';
}
}
}
// The following will redirect you to where ever you want
header('Location: https://aaa.com' . $url_endpoint);
/* Make sure that code below does not get executed when we redirect. */

One method would be to do the below using a switch statement.
This allows for easy growth and in the event you end up with a LOT of languages easy to just repeat and falls back to the site URL in the event there isn't a match.
add_action( 'wp_head', 'redirect_after_booking' );
function redirect_after_booking() {
if ( in_category('teachers') ) {
switch (CL_LANGUAGE_CODE) {
case 'zh-hant':
wp_redirect( trailingslashit( get_site_url() ) . CL_LANGUAGE_CODE );
exit;
break;
default:
wp_redirect( get_site_url() );
exit;
}
}
}

Related

show shortcodes according to url

I'm new to programming. Let's see if you can help me. I have to create a script to show several different short codes depending on the result of each url. They gave me this code but there's no way
<script>
var pages = window.location.href;
if((url == '/?listing_region=alicante')) {
echo do_shortcode( '[template id="11570"]' );
else {
if((url == '/?listing_region=madrid')) {
} echo do_shortcode( '[template id="11571"]' );
else {
if((url == '/?listing_region=barcelona')) {
} echo do_shortcode( '[template id="11570"]' );
}</script>

Woocommerce function that triggers jquery code

Iam trying to trigger a popup by simulating a button click with a simple JS function when a product from a specific category is added to the woocommerce cart. I have seen some do it in simmilair functions, but I cant figure this one to work.
I have composed the following function that runs if the category is in cart and if the page is the checkout page:
add_action( 'woocommerce_before_checkout_form', 'check_category_in_cart' );
function check_category_in_cart() {
$cat_in_cart = false;
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
if ( has_term( 'test', 'product_cat', $cart_item['product_id'] ) ) {
$cat_in_cart = true;
break;
}
}
if ( $cat_in_cart ) {
<script>
jQuery(document).ready(function($) {
$('#pop-up').trigger('click');
});
</script>
}
}
This function makes my website not function. Anyone has an idea how I can get this to work?
use setTimeout(). try the below code.
add_action( 'woocommerce_before_checkout_form', 'check_category_in_cart' );
function check_category_in_cart() {
$cat_in_cart = false;
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
if ( has_term( 'test', 'product_cat', $cart_item['product_id'] ) ) {
$cat_in_cart = true;
break;
}
}
if ( $cat_in_cart ) { ?>
<script>
jQuery(document).ready(function($) {
setTimeout(function(){
$('#pop-up').trigger('click');
}, 10);
});
</script>
<?php }
}
jQuery(document).ready(function($) {
setTimeout(function(){
$('#pop-up').trigger('click');
}, 10);
jQuery(document).on('click','#pop-up',function(){
alert('trigger');
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="pop-up">popup</button>
PHP waits for a php valid code in <?php ?> tags, but you are placing JavaScript, so you have to close the PHP tag before <script> and open a new one after the </script>. Otherwise your jQuery code is fine.
if ( $cat_in_cart ) {
?>
<script>
jQuery(function() {
$('#pop-up').trigger('click');
});
</script>
<?php
}
Reason need to check.
Maybe Because your id (pop-up) is not placed in your HTML.
Maybe your jQuery is not loaded.
Check in the console what kind of error you found.
your PHP function should properly closed.
if ( $cat_in_cart ) {
?>
<script>
jQuery(document).ready(function($) {
$('#pop-up').trigger('click');
});
</script>
<?php
}
if all is good then you can try.
jQuery(document).ready(function($) {
var timeInterVal = setInterval(CheckId, 1000);
CheckId function(){
var id = $("#pop-up");
if(id.length!=0){
$('#pop-up').trigger('click');
clearInterval(timeInterVal);
}
}
});
This will work if your Id not found once your id placed then this will stop the timer and trigger pop-up.
Thanks.

How to get post id in Ajax callback in Wordpress

I use the Add to cart Ajax callback, but I miss how I can get the post Id there.
MY GOAL: I want to use the add_filter only on a specific page.
PHP in functions.php
add_filter( 'woocommerce_add_cart_item_data', 'iconic_add_engraving_text_to_cart_item' , 10, 3 );
function iconic_add_engraving_text_to_cart_item( $cart_item_data, $product_id, $variation_id ) {
global $post;
if ( $post->ID === 54214 ) {
$engraving_text = 'test';
$cart_item_data['iconic-engraving'] = $engraving_text;
return $cart_item_data;
} else {
return $cart_item_data;
}
}
This is NOT WORKING because $post is NULL (because of the Ajax woocommerce_add_cart_item_data hook).
So I tried the following code in the JS to get the post id in JS (working).
function get_current_page_id() {
var page_body = $('body.page');
var id = 0;
if(page_body) {
var classList = page_body.attr('class').split(/\s+/);
$.each(classList, function(index, item) {
if (item.indexOf('page-id') >= 0) {
var item_arr = item.split('-');
id = item_arr[item_arr.length -1];
return false;
}
});
}
return id;
}
Now, how can I handover the id to my Ajax Callback to work with it?
Any advice?
EDIT:
I forgot to tell that I am planning to use the add to cart action on other pages but not a single product page.
For that, I am using a third party plugin which gives me the button for my desired product, so I am not using default $product or $post Object (like in single product pages).
I have finally found a solution for this "simple" problem. I can work with a session:
add_action( 'wp_head', 'set_session' );
add_filter( 'woocommerce_add_cart_item_data', 'iconic_add_engraving_text_to_cart_item' , 10, 3 );
function set_session() {
session_start();
// add post id
global $post;
$post_id = $post->ID;
$_SESSION['post_id'] = $post_id;
}
function iconic_add_engraving_text_to_cart_item( $cart_item_data, $product_id, $variation_id ) {
session_start();
if( $_SESSION['post_id'] == 54214 ) {
$engraving_text = 'test';
$cart_item_data['iconic-engraving'] = $engraving_text;
return $cart_item_data;
} else {
return $cart_item_data;
}
}

wordpress plugin jquery ajax call to function not working

JQuery Code:
jQuery("#dmhsc-form").on("submit", function () {
var form = this;
if (jQuery("input[name='url']", form).val() == "") {
jQuery("div[id='results']", form).html('<div class="not-available">Please, Enter site address.</div>');
return false;
}
var url = jQuery("input[name='url']", form).val();
jQuery("div[id='results']", form).css('display', 'none');
jQuery("div[id='results']", form).html('');
jQuery("div[id='loading']", form).css('display', 'inline');
var data = {
'action': 'dmhsc_show',
'url': url,
'security': badnc_ajax.dmhsc_nonce
};
jQuery.post(badnc_ajax.ajaxurl, data, function (response) {
var x = JSON.parse(response);
if (x.status >= 0) {
display = x.text;
} else {
display = "Error occured." + x;
}
jQuery("div[id='results']", form).css('display', 'block');
jQuery("div[id='loading']", form).css('display', 'none');
jQuery("div[id='results']", form).html(unescape(display));
});
return false;
});
Plugin File
function badnc_load_styles() {
wp_enqueue_script( 'badnc-script', plugins_url( 'script.js', __FILE__ ), array('jquery')); // script.js contains jquery code
wp_localize_script( 'badnc-script', 'badnc_ajax', array(
'ajaxurl' => admin_url( 'admin-ajax.php' ),
'dmhsc_nonce' => wp_create_nonce( 'dmhsc_nonce' ))
);
}
add_action( 'wp_loaded', 'badnc_load_styles' );
add_action( 'admin_enqueue_scripts', 'badnc_load_styles' );
function dmhsc_show() {
check_ajax_referer( 'dmhsc_nonce', 'security' );
if(isset($_POST['url']))
{
$url = sanitize_text_field($_POST['url']);
if(!$url || !is_string($url) || ! preg_match('/^(https?:\/\/)?(www\.)?\w+\.[a-z]{2,6}(\/)?$/i', $url)) {
$result = array('status'=>0,'url'=>$url, 'text'=> '<div class="not-available">Please, Enter valid domain name.</div>');
echo json_encode($result);
} else {
/*$result = array('status'=>0, 'text'=> '<div class="not-available">Domain: '.$url.'</div>');
echo json_encode($result);*/ //It display the message without calling to fucntion
check_https($url); //function call
}
}
die();
}
add_action('wp_ajax_dmhsc_show','dmhsc_show');
add_action('wp_ajax_nopriv_dmhsc_show','dmhsc_show');
function check_https($host) {
$result = array('status'=>0, 'text'=> '<div class="not-available">Domain: '.$host.'</div>');
echo json_encode($result);
}
Problem
I want to show "Domain: domain name" when I submit the form. Form contains url field and submit button.
but I don't know it is not displaying the message written in check_https() function.
I am also getting error in console:
Uncaught SyntaxError: Unexpected token { in JSON at position 74
at JSON.parse (<anonymous>)
If I display the message without calling to function check_https(), it works.
What should be the problem.

Call Jquery Function in Codeigniter

I have one if-else and I want to call function which contain jquery script. but its not working
Here is my codeignitor view code
Code
if($osoption == "windows")
{
?>
<script>
windows();
</script>
<?
$mysqldatabasehidden="N/A";
if ($_POST['mssqldatabasehidden']=="")
{
$mssqldatabasehidden = "1 No";
}
else
{
$mssqldatabasehidden = $_POST['mssqldatabasehidden']." No";
}
if($_POST['mssqlstoragehidden']=="")
{
$mssqlstoragehidden = "100";
}
else
{
$mssqlstoragehidden = $_POST['mssqlstoragehidden']." MB";
}
if($_POST['mssqltotalcosthidden'] =="")
{
$mssqltotalcosthidden = "3000 INR";
}
else
{
$mssqltotalcosthidden = $_POST['mssqltotalcosthidden'].".00 INR";
}
//echo ("mssql database =".$mssqldatabasehidden." <br>");
//echo ("mssql storage =".$mssqlstoragehidden." <br>");
//echo ("mssqltotalcost =".$mssqltotalcosthidden." <br>");
}
else
{
?>
<script>
linux();
</script>
<?
if($_POST['mysqldatabasehidden'] =="")
{ $mysqldatabasehidden = "0 No.";
$mysqldatabasecost="0.00 INR";
}
else
{
$mysqldatabasehidden = $_POST['mysqldatabasehidden']." No";
$mysqldatabasecost="0.00 INR";
//echo ("mysqldatabse =".$mysqldatabasehidden." <br>");
}
}
If windows selected than its call function name "windows" and same for "linux" when its in Else condition.
Here is my two functions
JQ Functions
<script>
function windows()
{
alert();
$("#divmssqldb").removeClass("divhide").addClass("divshow");
$("#divmssqlstor").removeClass("divhide").addClass("divshow");
$("#divmssqlprice").removeClass("divhide").addClass("divshow");
$("#divmysql").addClass("divhide");
}
function linux()
{
alert();
$("#divmssqldb").removeClass("divshow").addClass("divhide");
$("#divmssqlstor").removeClass("divshow").addClass("divhide");
$("#divmssqlprice").removeClass("divshow").addClass("divhide");
$("#divmysql").removeClass("divhide").addClass("divshow");
}
</script>
Remove the script which is written in your PHP code and call your functions after there definitions and declarations like,
<script>
function windows(){
alert('windows');
....
}
function linux(){
alert('linux');
....
}
$(function(){// add document ready function
<?php if($osoption == "windows") { ?> windows(); <?php } ?>
<?php if($osoption == "linux") { ?> linux(); <?php } ?>
});
</script>

Categories