DNI show div based on landing page, continue showing div entire session - javascript

I have about 60 landing pages that use different phone numbers on them. I am using a combination of WordPress and Advanced Custom Fields to place the phone numbers on their respective pages.
I am being asked to show a <div> based on the landing page URL that will not only show the phone number assigned to that page, but, keep showing the <div> (and phone number) regardless of what page the user navigates to on the website.
I have found little to no support on how to make the <div> remain visible throughout the entire session until the user closes the window.
I am thinking that this will somehow revolve around a cookie and Dynamic Number Insertion but I have no real progress to speak of. Should this be done using PHP or JS? Does a plugin exist that would allow for this on WordPress? I'm open to all suggestions.

Please try this code. Like #John C mentioned, WP Engine doesn't recommend Cookie nor PHP Session for the sake of performance and security. This is pure JavaScript code, and I think this will solve your problem.
Code in your Post/Page template file:
<div id="phone-number"></div>
<?php if( get_field('phone_number') ): ?>
<script type="text/javascript">
let phone_number = "<?php the_field('phone_number'); ?>";
</script>
<?php endif; ?>
Code in your theme JavaScript file:
<script type="text/javascript">
// in the case of the div data is persistent on the same site
// let storage = localStorage;
// in the case of the div data is persistent in the same tab, but not in new tab
let storage = sessionStorage;
let key = "phone_number"; // storage key
var global_phone_number = storage.getItem(key);
// check if storage data is set before
if (null === global_phone_number) {
// if not set the data on page into storage
global_phone_number = phone_number ? phone_number : '';
storage.setItem(key, global_phone_number);
}
document.getElementById('phone-number').innerHTML = global_phone_number;
</script>

You should use PHP and capture the session.
(untested code warning)
add_action('wp_footer', 'dynamic_phone_div');
function dynamic_phone_div() {
session_start;
if(isset($_SESSION['phone_div']) ? $phone_div = $_SESSION['phone_div'] :
$phone_div = '';
if($phone_div != '') {
echo '<div class="that_div_thing">';
echo $phone_div;
echo '</div>';
} else {
$_SESSION['phone_div'] = 123456789;
echo '<div class="that_div_thing">';
echo '123456789';
echo '</div>';
}
}
This is only raw logic. I am not sure where your div is (header/footer/page) - depending on where it is you should either use a hook (header/footer) or code it into a template (page/post).
The session will be destroyed after the user closes the tab/window.

I would probably do this with client side session storage. Providing all pages open in the same tab, the value will remain for the session, then be removed.
PHP code (in your functions.php file?) would be something like this:
function phone_script() {
$params = array(
'phone_number' => null, // Insert logic for current number. Can stay null if this is running on a non-landing page
'is_landing_page' => false // Change to true/false based on is current page a landing one or not
);
$params = json_encode( $params );
echo <<< EOT
<script>
let settings = $params;
document.addEventListener("DOMContentLoaded", function() {
if( settings.is_landing_page ) {
window.sessionStorage.setItem( 'phone-number', settings.phone_number );
} else {
settings.phone_number = window.sessionStorage.getItem( 'phone-number' );
}
if( settings.phone_number ) {
let div = document.createElement('div');
div.classList.add('phone-div');
// or add inline style
// div.style.cssText = 'position:fixed'; //etc
// Some logic here to actually add the number and any other content to the div
div.innerHTML = `The Phone number is: ${settings.phone_number}`;
document.body.appendChild(div);
}
});
</script>
EOT;
}
add_action( 'wp_footer', 'phone_script');
Note that the EOT; line MUST have no leading or trailing spaces.
The above is untested.

Related

how to store cookie when click on anchor

I am counting the clicks on anchors and store the number of clicks in a .txt file.
When click on an anchor, the number increases by 1.
I am not using a user management system, so to prevent multiple clicks on an anchor by a user, i need to store a cookie.
But i do have multiple anchors. If a user clicks on anchor 1, the number of click events on anchor 1 increases by 1. He should not have the possibility to click a second time on anchor 1, at least: it should not increase by 1 anymore.
But for that user, he still must be able to click on anchor 2 and anchor 3 and it should increase with 1. And after this, also these anchors should not increase by 1 anymore when user clicks on it.
How can i achieve this?
This is my html;
<?php
$clickcount = explode("\n", file_get_contents('counter.txt'));
foreach($clickcount as $line){
$tmp = explode('||', $line);
$count[trim($tmp[0])] = trim($tmp[1]);
}
?>
Like
<span class="click-count"><?php echo $count['count1'];?></span> likes.
Like
<span class="click-count"><?php echo $count['count2'];?></span> likes.
Like
<span class="click-count"><?php echo $count['count3'];?></span> likes.
The js:
$(document).on('click', '.click-trigger', function()
{
var data = {'id':$(this).attr('data-click-id')};
var count = $(this).next(".click-count");
$.ajax({
type : 'POST',
url : 'counter.php',
data : data,
success : function(data)
{
$(".click-count").fadeIn(500).show(function()
{
count.html(data);
});
}
});
return false;
});
And this is file counter.php
$file = 'counter.txt'; // path to text file that stores counts
$fh = fopen($file, 'r+');
$id = $_REQUEST['id']; // posted from page
$lines = '';
while(!feof($fh)){
$line = explode('||', fgets($fh));
$item = trim($line[0]);
$num = trim($line[1]);
if(!empty($item)){
if($item == $id){
$num++; // increment count by 1
echo $num;
}
$lines .= "$item||$num\r\n";
}
}
file_put_contents($file, $lines);
fclose($fh);
The file counter.txt looks like this:
count1||36
count2||124
count3||12
You can use serialize on an array of item numbers when setting the cookie value from php, and unserialize when reading the cookie. You will get an array of integers and can check with in_array whether the user has already clicked the link.

adding Advanced Custom Field to javascript

I have created an ACF option in the admin so a user can add cookie notice text via the admin...The javascript script I'm using creates the message within the javascript so I'm wanting to echo the ACF field within the javascript.
At the top of my cookie.js file I have: "<?php $cooke_msg = the_field('cookie_notice', 'option'); ?>"; and I'm echoing it within a var like so: var msg = "<?php echo $cookie_msg; ?>"; so the top of my file looks like this:
"<?php $cooke_msg = the_field('cookie_notice', 'option'); ?>";
(function(){
//Change these values
var msg = "<?php echo $cookie_msg; ?>";
var closeBtnMsg = "OK";
var privacyBtnMsg = "Privacy Policy";
var privacyLink = "https://www.google.com";
//check cookies
if(document.cookie){
var cookieString = document.cookie;
var cookieList = cookieString.split(";");
// if cookie named OKCookie is found, return
for(x = 0; x < cookieList.length; x++){
if (cookieList[x].indexOf("OKCookie") != -1){return};
}
}
What I'm getting when I view the site is: <?php echo $cookie_msg; ?> and not the actual message from ACF...is there a way of actually doing this?
Wordpress giving nice function to pass PHP variable data to js file.
Put this code in your theme functions.php page.
function mytheme_load_scripts() {
wp_enqueue_script('mytheme-script', get_template_directory_uri() . '/js/mytheme-script.js');
wp_localize_script('mytheme-script', 'mytheme_script_vars', array(
'alert' => get_field("cookie_notice",$post_id)
)
);
}
add_action('wp_enqueue_scripts', 'mytheme_load_scripts');
And Create one js folder in your theme root directory. Inside that directory create the js file named mytheme-script.js file, & put the below code over there.
jQuery(document).ready(function($) {
alert( mytheme_script_vars.alert );
});
Now visit any page of your site. Surely you will get an alert with the your desire field value. Make sure you will assign proper value to $post_id. I think this will help you. Codex reference link for more details: WP Localize Script Function

How do I display a <div> when the URL contains the ID?

I need to display certain content on the document when the URL contains that particular content's ID. Currently, the USER will go through a series of steps for a security check. At the end, a cookie will be placed on their system to avoid doing the security check in 30 days. Now, let's say that the cookie fails to go on the system or it fails to locate the cookie on the user's system, there has to be a notice so the user doesn't get confused on why they are getting another security check before 30 days. So far, this is what I got:
Places the cookie on the computer (setcookie.php):
<?php
$cookie_name = "securitycheck";
$cookie_value = "29610741351979104njnj23j52nx72d72n892ccr3179hd3";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day
?>
Validates cookie (checkcookievalidation.php):
<head>
<?php
$cookie_name = "securitycheck";
?>
</head>
<body>
<?php
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie named '" . $cookie_name . "' is not set! Internal Error!";
header( 'Location: checkfinished.php?nocookieset' ) ;
} else {
echo "Cookie '" . $cookie_name . "' is set!<br>";
header("Location: checkfinished.php");
}
?>
</body>
Finished page (checkfinished.php) [This is where I'm stuck on]:
<div id="nocookieset" style="visibility: visible;" align="center"><h3>Although the check did complete with errors. We were unable to set the cookie due to an internal server error. Please contact the web team about this if the issue continues.</h3></div>
-
Now I need it to show the Div with the nocookieset id if the URL contains the id in there (such as http://example.com/example.php?nocookieset)
If it doesn't contain ?nocookieset in the URL, then it won't show the Div.
How can I make this happen?
The best way to do this is to inject the HTML content inside a PHP condition:
<?php
if(isset($_GET['nocookieset'])) {
?>
<div id="nocookieset">
</div>
<?php
/* Don't forget to close the condition logic! */
}
?>
That way the nocookieset DIV will only get outputted to the page if the GET variable is set :)
Hope this helps! :)
Using JS:
<script>
if(location.search === "?nocookieset") document.getElementById("nocookieset").style.visibility="visible";
</script>
Version that supports more than one ID:
<script>
var supportedIds = ["nocookieset", "toomanycookiesset"];
if(supportedIds.indexOf(location.search.substr(1))>-1) {
document.getElementById(location.search.substr(1)).style.visibility="visible";
}
</script>
In PHP (i.e. checkfinished.php), check if the GET variable is set, using the superglobal $_GET...You could use various techniques to check if the index is set (e.g. isset(), array_key_exists)...
if (array_key_exists('nocookieset',$_GET)) {
echo '<div id="nocookieset" style="visibility: visible;" align="center"><h3>Although the check did complete with errors. We were unable to set the cookie due to an internal server error. Please contact the web team about this if the issue continues.</h3></div>';
}
You could also check in the client-side, e.g. with Navigator.cookieEnabled - see this guide for more information. Following this technique, the need for checkcookievalidation.php would be eliminated.
Note: in the sandbox example below, usage of document.cookie is disabled but you can see it in action in this plunker.
document.addEventListener('DOMContentLoaded', function() {
var element = document.getElementById('message');
cookiesEnabled = false; //set tentatively
if (navigator.cookieEnabled) {
//document.cookie = "testcookie";
//cookiesEnabled = (document.cookie.indexOf("testcookie") != -1) ? true : false;
//we can't set cookies in this sandbox so set it to true for now
cookiesEnabled = true;
}
if (cookiesEnabled) {
element.innerHTML = 'Yes';
} else {
element.innerHTML = 'No';
}
});
<span style="font-style: italic;">Are Cookies Enabled? </span><span id="message"></span>

Save advert click to database using PHP, then open link

I am creating a WordPress widget that shows and advert. When the advert is clicked I want to record the clicks with some detail.
The database table is already created and entries can be saved correctly using the function f1_add_advert_click($advert_id) in save-advert-click.php, which resides in the same directory as the Widget's PHP that I want to call it from (the plugin's root directory).
Requirements:
link will be on a piece of text, just a plain a href
a visitor should see the target link when he hovers his cursor over the link, not appended by a parameter for the next page
no 'middle' page that registers the click then redirects onto the target page. Just straight from the origin to the target.
secure: the advert ID is passed on to the f1_add_advert_click function and then inserted into the database. I would like to be sure that it's the correct ID (not something a visitor could change).
there can be multiple instances of this Widget on a page
I have seen and tried a lot of examples on Stackoverflow, but either I don't get it or the situation there is different from mine. Would gladly appreciate a well commented code example that works in my situation. Please be aware that I am not a seasoned programmer, especially 'green' when it comes to JavaScript and jQuery.
From what I have read on the web I think I should be using AJAX to first register the click, then send the browser to the target page. Not sure if I have to use onclick or not, based on the bottom answer of this post.
Have put in about four hours so far on this part. Now asking for help. Not much code to show, because I deleted everything that didn't work.
This is what I have currently got within the widget function of the plugin (left out the regular php showing title and so on):
<script type="text/javascript">
function myAjax() {
$.ajax({
type: "POST",
url: './wp-content/plugins/facilitaire-advert-widget/save-advert-click.php',
data:{action:'call_this'},
success:function(html) {
alert(html);
}
});
}
</script>
Followed by the link and the click action
<p>Link of Advert
Then these are my contents for save-advert-click.php
// check for action signal
if($_POST['action'] == 'call_this') {
f1_add_advert_click ();
}
/**
* Records a click event in the database
*/
function f1_add_advert_click ()
{
$advert_id = random_int(1,300); // change to $clicked_advert_id later
$user_ip = get_user_ip();
global $wpdb;
$table_name = $wpdb->prefix . 'f1_advert_clicks';
$wpdb->insert( $table_name, array(
'advert_id'=> $advert_id,
'user_agent'=> $_SERVER['HTTP_USER_AGENT'],
'ip_address'=> $user_ip
),
array(
'%d',
'%s',
'%s'
)
);
}
/**
* Get user IP
*/
function get_user_ip()
{
$client = #$_SERVER['HTTP_CLIENT_IP'];
$forward = #$_SERVER['HTTP_X_FORWARDED_FOR'];
$remote = $_SERVER['REMOTE_ADDR'];
if ( filter_var($client, FILTER_VALIDATE_IP) ) {
$ip = $client;
} elseif ( filter_var($forward, FILTER_VALIDATE_IP) ) {
$ip = $forward;
} else {
$ip = $remote;
}
return $ip;
}
UPDATE WITH SOLUTION
Thanks to #mplungjan's suggestion I updated my code to the following, working code. Please note some differences with #mplungjan's code, because I had to make some adjustments to make it work in WordPress.
contents of bottom part of show-advert.php
<script>
jQuery(function() {
jQuery(".advertLink").on("click",function(e) {
e.preventDefault(); // stop the link unless it has a target _blank or similar
var href = this.href;
var id= <?php echo $advert_id; ?>;
jQuery.post("<?php echo get_home_url(); ?>/wp-content/plugins/facilitaire-advert-widget/save-advert-click.php",
{ "action":"register_click", "advert_id":id },
function() {
location=href;
}
);
});
});
</script>
Link of Advert<br />
<?php
Then in the top part of save-advert-click.php I have
<?php
// check for action signal
if($_POST['action'] == 'register_click') {
f1_add_advert_click( $_POST["advert_id"] );
}
/**
* Records a click event in the database
*/
function f1_add_advert_click ( $advert_id )
{
$user_ip = get_user_ip();
// need to load WordPress to be able to access the database
define( 'SHORTINIT', true );
require_once( '../../../wp-load.php' ); // localhost needs this, production can have require_once( $_SERVER['DOCUMENT_ROOT'] . '/wp-load.php' );
global $wpdb;
$table_name = $wpdb->prefix . 'f1_advert_clicks';
$wpdb->insert( $table_name, array(
'advert_id'=> $advert_id,
'user_agent'=> $_SERVER['HTTP_USER_AGENT'],
'ip_address'=> $user_ip
),
array(
'%d',
'%s',
'%s'
)
);
}
You will want to do something like
$(function() {
$(".advertLink").on("click",function(e) {
e.preventDefault(); // stop the link unless it has a target _blank or similar
var href = this.href;
var id=this.id; // or $(this).data("advertid") if you have data-advertid="advert1" on the link
$.post("./wp-content/plugins/facilitaire-advert-widget/save-advert-click.php",
{ "action":"call_this", "advert_ID":id },
function() {
location=href; // or window.open
}
);
});
});
using
Link of Advert

Unable to make JSONP requests to Google Search webpage

This is my fiddle http://jsfiddle.net/x06Lr919/4/
$.getJSON('http://google.com/search?&q=hi&callback=?',
function(data) {
console.log(data);
$("#target").html(data.contents);
});
I would like to fetch the whole HTML of "http://google.com/search&q=hi" as string of this webpage. I know of this website : www.whateverorigin.org that lets me do it but I don't want to use any other external websites for this purposes.
I know, we have to use JSONP, and hence I've added the callback.
I'm unable to understand the type of data that is returned. Tried JSON.stringify but wasn't helpful.
You could scrape like this:
<?php
function searchGoogle($query, $pages = 1){
$r = array();
for($i=0,$n=0; $i<$pages; $i++,$n+=10){
$doc = new DOMDocument;
#$doc->loadHTMLFile('https://www.google.com/search?q='.urlencode($query)."&start=$n");
$c = $doc->getElementsByTagName('cite');
foreach($c as $e){
if($e->hasAttribute('class') && $e->getAttribute('class') === '_Rm'){
array_push($r, $e->nodeValue);
}
}
}
echo json_encode($r);
}
/* on your JavaScript page
$.post('thisURL.php', {search:'Anything you want to search here.', pages:2}, function(urlsArray){
// handle urlsArray here
});
*/
if(isset($_POST['search'], $_POST['pages'])){
searchGoogle($_POST['search'], $_POST['pages']); // 20 results
}
?>

Categories

Resources