On a wordpress website I'd like to display "button one" when the url doesn't contain "/en/" path, and display "button two" when url contains "/en/".
The button' html look like this:
<a href="https://www.google.com" >Button one</span></a>
<a href="https://www.yahoo.com" >Button two</span></a>
I've been trying many variations of this approach:
<script type="text/javascript">
if(window.location.href.indexOf("/en/") > -1) {
document.getElementsByClassName("microwidget-btn mini-button header-elements-button-1 show-on-desktop").style.display = 'none';
document.getElementsByClassName("microwidget-btn mini-button header-elements-button-2 show-on-desktop").style.display = '';
} else {
document.getElementsByClassName("microwidget-btn mini-button header-elements-button-1 show-on-desktop").style.display = '';
document.getElementsByClassName("microwidget-btn mini-button header-elements-button-2 show-on-desktop").style.display = 'none';
}
</script>
But nothing happen and in the console I get
Uncaught TypeError: document.getElementsByClassName(...)[0] is undefined
Thank you
CodePudding user response:
you can use this wordpress code for it
global $wp;
$currenturl = home_url( $wp->request )
$find= '/en';
if (strpos($currenturl, $find) !== false) {
?>
<a href="https://www.google.com" >Button one</span></a>
<?php
}else{
?>
<a href="https://www.yahoo.com" >Button two</span></a>
<?php
}
CodePudding user response:
You could use JavaScript to check if the url contains a specific language like so
document.addEventListener("DOMContentLoaded", function() {
if(window.location.href.indexOf("/en/") > -1) {
// en page
// Show button 2
document.getElementById('button-one').style.display = 'none';
document.getElementById('button-two').style.display = 'flex';
} else {
//Show button 1
document.getElementById('button-one').style.display = 'flex';
document.getElementById('button-two').style.display = 'none';
}
});
Please notice that I changed you html code. I added an id property and style tag with display: none as default
<a href="https://www.google.com" id="button-one" style="display:none" >Button one</span></a>
<a href="https://www.yahoo.com" id="button-two" style="display:none">Button two</span></a>