I'm using this code in functions.php on WordPress to generate an affiliate link based on the visitor location, It's working perfectly but the problem is that if page caching is turned on (W3 Total Cache), The variables get cached so if someone from the UK was the first one to open the page then the second one from Germany opened the page he will get the same link that the first visitor got.
One more thing please, I'm still very new to PHP and javascript so I would appreciate if the answer was simplified enough.
<?php
add_action( 'woocommerce_before_add_to_cart_button', 'affiliate_link', 10);
function affiliate_link() {
$not_avilable_country = '<div id="amz_not_avilable" class="amz_not_avilable">This product is not avilable in your country yet</div>';
// IP Geolocation
$country_code = $_SERVER ["HTTP_CF_IPCOUNTRY"];
// Get Custom Fields
$de_asin = get_post_meta(get_post()->ID, "wccaf_de_asin", true );
$uk_asin = get_post_meta(get_post()->ID, "wccaf_uk_asin", true );
//////////////////////////////////////////////
if ($country_code=="DE" or $country_code=="DE") {
$amazon_domain = 'https://www.amazon.de';
// $associate_id = 'bonstato-21';
$asin = $de_asin;
}
else if ($country_code=="GB" && $uk_asin!=="") {
$amazon_domain = 'https://www.amazon.co.uk';
// $associate_id = 'bonmedico-21';
$asin = $uk_asin;
}
///////////////////////////////////////////////
if( wp_is_mobile() ) {
// Amazon Link For Mobile
?>
<script>
function amzGo(){
window.location='<?php echo $amazon_domain ?>/dp/<?php echo $asin ?>/?tag=<?php echo $associate_id ?>';
}
</script>
<?php
}
else {
// Amazon Link For PC
?>
<script>
function amzGo(){
window.location='<?php echo $amazon_domain ?>/gp/aws/cart/add.html?AssociateTag=<?php echo $associate_id ?>&ASIN.1=<?php echo $asin ?>&Quantity.1=1';
}
</script>
<?php
}
?>
<div class="buy_amz_btn_wrap" >
<button type="button" id="buy_amz_btn" class="buy_amz_btn" onclick="amzGo();"><i class="fa fa-amazon fa-amz"></i><?php echo $amz_btn_title ?></button>
</div>
<?php
}
?>
A way to deactivate/disable W3 Total Cache on specific pages is to use another plugin called: "Plugin Organizer" by Jeff Sterup.
After installing and enabling it, go to settings (of the plugin) and follow the instructions to set it in the right way.
Once the plugin is enabled and settings are saved correctly, when you edit/create a new page using the editor you can see a checkbox that's show you which plugin to enable for that particular page and which to disable.
In this way you can disable W3 Total Cache on the page that's use your function on functions.php.
Hope it helps.
The most common way to bypass the cache is to serve this data via the WordPress json api and use java script to put the always fresh data into place.
The problem is not that the variable inside the code is being cached; what happens is that W3 Total Cache grabs the first page produced by your PHP code and store it in the hard disk of the server. Thenceforth, the browsers' requests are answered delivering the HTML static file stored in server's hard disk (PHP will not produce the same page again).
To solve this problem, you must transfer the "intelligence" inside your PHP code, which is responsible for create slightly different versions of your page, to your Javascript code. Bastian Haustein suggested one way to do that, using WordPress REST API. However, I would try first doing it in a simpler way: after page load, capture the link of your cached page and modify it according to the location of your visitor. Naturally, you will have to capture visitors geolocation also using JS - see the link suggested by cjmling: How to get visitor's location (i.e. country) using geolocation?
Related
I am editing a plone page to open an Excel document on a specific sheet. I created two buttons to see if either would appear as actual buttons and use the JS function I reference. With this code the exact part of the page looks like the image below.
Why is only text showing instead of the button and why is the onclick attribute not working?
Note: I have changed to links to the spreadsheet for posting it on here but the link has been tested on other webpages
<script type="text/javascript">
function Open_Excel_File(path,sheet)
{
fso = new ActiveXObject("Scripting.FileSystemObject");
if (!fso.FileExists(path))
alert("Cannot open file.\nFile '" + path + "' doesn't exist.");
else
{
var myApp = new ActiveXObject("Excel.Application");
if (myApp != null)
{
myApp.visible = true;
Book = myApp.workbooks.open(path);
var excel_sheet = Book.Worksheets(sheet).Activate;
myApp.range(f_range).Select;
}
else {
alert ("Cannot open Excel application");
}
}
}
</script>
<div>
<button onclick='Open_Excel_File("file://///fs-01\Departments\Underwriting\Statistical%20Data%20and%20Medical%20Information\Statistics\Cancers\Cancer%20Statistics%\Cancer%20Statistics%.xlsx", "Vulvar Ca");'>Open File</button>
<input type="button" onclick="Open_Excel_File('file://///fs-01\deps\uw\stat%20Data%20and%20Medical%20Information\Statistics\Cancers\Cancer%20Statistics%202018\Cancer%20Statistics%.xlsx', 'VCA');'>OPEN FILE</input>
</div>
your onclick value is not a function, it is the result of a function call. Try to change that to onclick="Open_Excel_File"; You'll have to provide the file path at some point
Accessing file system from browser is super restricted for security matters, the only way I see fit is to have a file input and using what user provides
Also Plone filter out a bounce of potential "nasty" tags through a specific configurable tool.
It seems to me that you have injected the in the source HTML of a Page (document) type.
If so, you will see in your browser that in, the page source code, the script tag has been totally stripped away.
So,
a correct way to inject some js in your page, is to load it as portal_javascript resource (plone<=4) or in resource_registry (plone>=5).
tha nasty way is to access, in the ZMI, at https://yourseite:8080/Plone/portal_transforms/safe_html/ and configure it to accept script tags inside a document (all document in your site actually).
If this answer does not satisfy you try to ask in the official community:
http://community.plone.org
hth,
alessandro
I want my code when someone clicks the link then a link will open random of 3 posts between */android.html ,*/samsung.html and */xiaomi.html.
My code is like this
<?php
$YuuClass->update_dls($file['downloads'], $file_id);
echo '<script type="text/javascript">
var x=Math.floor((Math.random()*3)+ 1);
var xxx=null;
if(x=="1"){xxx="android.html"}
if(x=="2"){xxx="samsung.html"}
if(x=="3"){xxx="xiaomi.html"}
</script>';
redirect('https://safelink-ainodorama.blogspot.com/2017/02/"+xxx+"?url='.base64_encode($copy['webContentLink']));
exit();
?>
Where "+xxx+" will change random between */android.html ,*/samsung.html and */xiaomi.html when I click it.
I tried to click it with code like that only showing base64code.
Ex-link when I click
http://myweb.web.id/0aHR0cHM6Ly9kcml2ZS5nb29nbGUuY29tL2Evc2RuMTgzcGVrYW5iYXJ1LnNjaC5pZC91Yz9pZD0xMUNoa0JpS3lvWkRMMGIxTWxYek4yeUt2NGRQcnJoMG8mZXhwb3J0PWRvd25sb2Fk
I want when I click it the URL will be like this
https://safelink-ainodorama.blogspot.com/2017/02/android.html?url=base64_code_here
where android.html can change randomly from 2 another page android, Samsung and Xiaomi.
Because javascript is client-side and php is server-side the javascript wont change xxx.
Instead have an array of your pages, then use array_rand to pick a random one.
Something like:
<?php
$YuuClass->update_dls($file['downloads'], $file_id);
$page = [
'android.html',
'samsung.html',
'xiaomi.html'
];
$url = 'https://safelink-ainodorama.blogspot.com/2017/02/'.$page[array_rand($page)].'?url='.base64_encode($copy['webContentLink']);
redirect($url);
exit;
how is it possible to achieve this:
http://jennamolby.com/how-to-display-dynamic-content-on-a-page-using-url-parameters/
using php?
let's say that I have the following a url:
http://localhost:8888/index.php?page=pages-folder/works-folder/content-manager?article=my-article
to get there I have a link in pages-folder/works.php :
link
which should open content-manager.php in which inside a div I should load my-article.php
EDITED:
I have an index file in which a load into the div.container all the pages I need, so in this case my works.php file is loaded int the div.container using using:
<?php
$page = $_GET['page'];
if(!empty($page)){
$page .= '.php';
include($page);
}
else {
include('pages/home.php');
}
since I also needed to update the url without reloading the page I use this script:
function ChangeUrl(page, url) {
if (typeof (history.pushState) != "undefined") {
var obj = { Page: page, Url: url };
history.pushState(obj, obj.Page, obj.Url);
}
}
$('ul.menu li a').on('click', function(){
var page = $(this).attr('href');
var pageUrl = page.split("/");
pageUrl = pageUrl[1];
$('.container').load(page + '.php', function(){
//fadeout old content
//fadein new content
});
ChangeUrl('Page1', '?page=' + page);
return false;
})
once I have my works.php loaded into the div.container I have the above mentioned link which should lead me to: pages-folder/works-folder/content-manager.php
it is in this page where I'd like to load my-article.php inside the main div of content-manager.php
I thought that adding the ?article= variable would have worked using the same system as above:
$article = $_GET['article'];
if(!empty($article)){
$article .= '.php';
include($article);
}
else {
...
}
but it doesn't...
how can I achieve this?
Why you don't just add you article as a query param ?
http://localhost:8888/index.php?page=pages-folder/works-folder/content-manager&article=my-article
and make a link like this
link
This is just an exemple to understand what you want to do, don't use this kind of code in production, he is vulnerably to CSRF attack
EDIT: with echo it's better sorry
I haven't answered your question per se but this is the sort of code you are looking for:
<?php if (isset($_GET["page"]) && strtolower($_GET["page"]) == "1") { ?>
<p>You are on page one</p>
Back
<?php } elseif (isset($_GET["page"]) && strtolower($_GET["page"]) == "2") { ?>
<p>You are on page two</p>
Back
<?php } else { ?>
<p>You have not selected a page. Click one of the links:</p>
Page one
Page two
<?php } ?>
Explanation
How does $_GET work?
$_GET is a super global variable - meaning it can be accessed from anywhere.
It is a an associative array of variables passed to the current script via the URL parameters.
These are specified following a question mark (?) in the URL. To specify multiple parameters you must use the ampersand (&) character between each one.
$_GET must be specified at the end of the URL after everything else.
http://www.example.com/thisPage.php?page=a
http://www.example.com/thisPage.php?page=a&theme=light
The first URL will produce a $_GET with one element which can be accessed as: $_GET["page"] and would return a string of one character a.
The second will produce:
$_GET["page"]; // returns "a"
$_GET["theme"]; // returns "light"
Notice that for each parameter a new key-value pair is created.
I wrote a comprehensive explanation of superglobals on SO Documentation, but that has since been deprecated. RIP my hard work :P
Showing differing content
As you can see from my answer above. You can use simple if statements to check what the value is.
Firstly, ensure that $_GET isset and then check the value.
I have converted the value of the array to lowercase since "A" is not the same as "a".
The example you linked to really over-complicates things. There is honestly no need for all that regular expressions, and it also relies on JavaScript which is not necessarily a good idea.
With my example at the top, there is no difference between user experience as PHP is server sided thus all the content is worked out and then served to the user.
One step further
Using this you can go that extra step and have an event listener and combine it with AJAX.
Altering my initial example you can have the following.
I have used the jQuery library as it is a lot easier to implement.
<div id="test">
<?php if (isset($_GET["page"]) && strtolower($_GET["page"]) == "1") { ?>
<p>You are on page one</p>
Back
<?php } elseif (isset($_GET["page"]) && strtolower($_GET["page"]) == "2") { ?>
<p>You are on page two</p>
Back
<?php } else { ?>
<p>You have not selected a page. Click one of the links:</p>
Page one
Page two
<?php } ?>
</div>
function myAJAX() {
$("a").on("click", function(e) {
e.preventDefault();
// get the clicked page number
if (this.href.indexOf("&") > -1) {
var d = this.href.substring(this.href.indexOf("page=") + "page=".length, this.href.indexOf("&"))
} else {
var d = this.href.substr(this.href.indexOf("page=") + "page=".length)
}
$.ajax({
method: "GET",
url: "t.php",
data: "page=" + d,
success: function(data, textStatus, jqXHR) {
// change the content of the #test div
$("#test").html($($.parseHTML(data)).filter("#test")[0]);
myAJAX();
}
});
});
}
myAJAX();
Notice that the HTML is not being wrapped in <div id="test"> which is so that the JavaScript can find that element and change it in the function.
$("#test").html($($.parseHTML(data)).filter("#test")[0]); is the line that is fetching the HTML and changing it with the data from the page you tried to click on.
I also call the function inside itself so that it will reattach on the anchor links. If you remove this line then the page will redirect as normal.
The good thing about this implementation is that if your user does not have JavaScript then the page will act as normal and there will be a normal reload of the site.
No need for any extra work on your part.
I know this is almost duplicated, a lot of people asked that and a lot answered them by PHP Form but I really didn't find anything for my problem.
I have a page called platforms.php and this page has a group of image-links which are: Windows,Mac, Android and iOS.
So what I want is when somebody clicks the Windows link (as an example) they go to a page called download.php and the page should say You are using Windows!.
Please not that I don't want to create a page for every link, I want it to be one page only.
Thanks in advance!
Make URL like that
<a href = "http://example.com/download.php?device=window" >Window</a>
<a href = "http://example.com//download.php?device=mac" >Mac</a>
On your page download.php
if(isset($_GET['device'])) {
$device = $_GET['device'];
}
if ($device == 'window' ) {
// window message here
} elseif ($device == 'mac' ) {
// mac message here
}
send an extra parameter in your url and then in the same single page use the condition like:
let the parameter name be 'pagetype'.
download.php
if ($_REQUEST['pagetype'] == 'windows')
{
//your output for windows
}
else if ($_REQUEST['pagetype'] == 'mac')
{
//your output for mac
}
else if(..)
{
.
.
.
Note:
You can replace $_REQUEST, with $_GET or $_POST, depending on method you use to post data to this page
You can have an HTML link and send the data through GET parameters. Something like (in platforms.php):
<a href="download.php?os=Windows >Windows</a>
<a href="download.php?os=Mac >Mac</a>
<a href="download.php?os=Android >Android</a>
<a href="download.php?os=iOs >iOs</a>
And then in downloads.php, getting the variable "os" and do whatever you want with it:
if ( isset($_GET['os'] ) ) {
echo "You are using " . $_GET['os'];
}
you can add image like
<img src="window.jpg"/>
<img src="ios.jpg"/>
and on download.php page you can check
$value = $_GET['key'];
if(value== 'window')
if(value== 'ios')
etc
hope this is what you want.
EDIT:
Adding the following to the code below:
alert(LogoutURL);
shows the URL is coming across to the JS variable incorrectly. Is seems to be "encoded" once passed to the JS var.
I know this from executing in my PHP the following:
<?php echo wp_logout_url('/') ?>
as this writes the correct URL to the page. Any help is appreciated. Thanks
I am sure this one is straightforward but I have not been able to find how to do this. Maybe I have asked the question wrong... I am trying to insert the "logout with no confirmation" link in WordPress but the URL I pass the menu does not resolve correctly. The menu is part of a theme so I cannot easily modify it.
As such I am using a combination of JS and PHP to generate the link for the current logged in user, by changing the "href" in the "a" item containing "Logout" text, to the output of "wp_logout_url" as follows:
<script type="text/javascript">
jQuery( document ).ready(function() {
/*** change Logout URL if logged in ***/
var LogoutURL = "<?php echo wp_logout_url('/') ?>";
jQuery('a').filter(function(index) { return jQuery(this).text() === "Logout"; }).attr("href", LogoutURL);
My resolved menu code:
<li id="menu-item-5516" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-5516">
Logout
</li>
When the JS inserts the resolved URL it seems to add "amp;" to it in places where it found "&". I even tried without success to use "encodeURI()" function.
How can I pass the URL to the HREF "as is"?
The issue seems to be that wp_logout_url is correctly changing & to &, and then jQuery must be again changing & to & resulting in &.
The hacky solution is to simply do
jQuery('a').filter(function(index) { return jQuery(this).text() === "Logout"; })
.attr("href", LogoutURL.split("&").join("&"));
Also, if you parent li elements id doesn't change, it would be far more efficient to do
$("#menu-item-5516").find("a").attr("href", ...);
Rather than run a filter on all of the a elements. If not I would still find a better way to select that element, checking every link in the document is overkill.
Note: You SHOULD have one amp; after every & in a link. That is CORRECT. If you DON'T want that, you can do
jQuery('a').filter(function(index) { return jQuery(this).text() === "Logout"; })
.attr("href", LogoutURL.split("&").join("&"));
Well this did it... still not sure why this is required. Am I pulling into the JS the url incorrectly?
var LogoutURL = "<?php echo wp_logout_url('/') ?>";
jQuery('a').filter(function(index) { return jQuery(this).text() === "Logout"; }).attr("href", LogoutURL.replace(/&/g, "&"));
This is my solution to place a logout link in my menu's list item with class "logout". The link now carries me through to the login page without the "oops ... do you really want to logout?":
PHP - replacing & with &:
$logouturl = str_replace('&','&',wp_logout_url(home_url() . "/wp-login.php?loggedout=true"));
jQuery - replacing href in li.logout a:
logoutUrl = '<?php echo $logouturl; ?>';
jQuery('li.logout a').attr('href',logoutUrl);