I want to encode my custom field links in Wordpress. I use a plugin to generate my custom field : Advanced Custom Fields.
I found a code with Php and JS
In single.php
function cl($url) {
$taille = strlen($url);
$urlcode = "";
for ($i = 0; $i < $taille; $i++) {
if ($i % 2) {
$urlcode.= "ajoutdunechainedecaractere" . $url{$i};
}
else {
$urlcode.= $url{$i};
}
}
return base64_encode($urlcode);
}
I have a JS file
function btob(text) {
text = text.replace(/\s/g,""); if (!(/^[a-z0-9\+\/\s]+\={0,2}$/i.test(text)) || text.length % 4 > 0) { return text; }
var digits = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/', cur, prev, digitNum, i=0, result = [], text = text.replace(/=/g, "");
while (i < text.length){
cur = digits.indexOf(text.charAt(i)); digitNum = i++ % 4;
switch (digitNum) {
case 1: result.push(String.fromCharCode(prev << 2 | cur >> 4)); break;
case 2: result.push(String.fromCharCode((prev & 0x0f) << 4 | cur >> 2)); break;
case 3: result.push(String.fromCharCode((prev & 3) << 6 | cur)); break;
}
prev = cur;
}
return result.join('');
}
function transformText() {
var s = document.getElementsByTagName('span');
for (i = 0; i < s.length; i++)
if ((s[i].className.indexOf('lc') != -1)){
var lien = btob(s[i].getAttribute('data')).replace(/ajoutdunechainedecaractere/g,"");
var lnk = document.createElement('a');
lnk.href = lien;
lnk.innerHTML = s[i].innerHTML;
s[i].innerHTML = '';
s[i].appendChild(lnk);
if( s[i].hasAttribute("onclick") )
//on récupère l'attribut onclick pour l'ajouter dans le lien
{
lnk.setAttribute('onclick', s[i].getAttribute('onclick'));
}
}
}
window.onload=transformText;
To display my link without encoding it I need to put that in my single.php
<?php the_field(lien); ?>
For encoding link I need replace this by that code, encoded is OK:
<span class="lc" data="<?php echo cl("http://www.exemple.com"); ?>" onclick="test()"> MY ANCHOR </span>
But if I replace " http://www.exemple.com " with my customfield
<span class="lc" data="<?php echo cl(the_field(lien)); ?>" onclick="test()"> MY ANCHOR </span>
I don't have an encoded url, only a normal url.
So please what am I doing wrong ?
Thanks for your help.
You need get_field
: http://www.advancedcustomfields.com/resources/functions/get_field/
<span class="lc" data="<?php echo cl(get_field(lien)); ?>" onclick="test()"> MY ANCHOR </span>
the_field
actually echos the value, get_field
returns it.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.