I wrote below code but facing issue to run it only on archive, categories, author, date pages to improve page speed.
add_action( 'wp_footer', function () { ?>
<script>
if( is_archive || is_category() || is_author() || is_date()) {
// targets spans containing text
let CalendarPrevBtn = document.getElementsByClassName("wp-calendar-nav-prev");
let CalendarNextBtn = document.getElementsByClassName("wp-calendar-nav-next");
// stores spans text
let PrevBtnText = CalendarPrevBtn[0].textContent;
let NextBtnText = CalendarNextBtn[0].textContent;
// deciding if btn needs to be hidden
Array.from(CalendarPrevBtn).forEach((x) => {
if (!PrevBtnText.trim()) {
x.style.display = "none";
} else {
// x.style.display = "block";
}
});
Array.from(CalendarNextBtn).forEach((x) => {
if (!NextBtnText.trim()) {
x.style.display = "none";
} else {
// x.style.display = "block";
}
});
}
</script>
<?php } );
When I run this code it says:
Uncaught ReferenceError: is_single is not defined
I wrote below code but facing issue to run it only on archive, categories, author, date pages to improve page speed.
add_action( 'wp_footer', function () { ?>
<script>
if( is_archive || is_category() || is_author() || is_date()) {
// targets spans containing text
let CalendarPrevBtn = document.getElementsByClassName("wp-calendar-nav-prev");
let CalendarNextBtn = document.getElementsByClassName("wp-calendar-nav-next");
// stores spans text
let PrevBtnText = CalendarPrevBtn[0].textContent;
let NextBtnText = CalendarNextBtn[0].textContent;
// deciding if btn needs to be hidden
Array.from(CalendarPrevBtn).forEach((x) => {
if (!PrevBtnText.trim()) {
x.style.display = "none";
} else {
// x.style.display = "block";
}
});
Array.from(CalendarNextBtn).forEach((x) => {
if (!NextBtnText.trim()) {
x.style.display = "none";
} else {
// x.style.display = "block";
}
});
}
</script>
<?php } );
When I run this code it says:
Share Improve this question asked Mar 20, 2023 at 12:51 SunnySunny 31 bronze badgeUncaught ReferenceError: is_single is not defined
1 Answer
Reset to default 0None of those functions are JavaScript functions. They're PHP functions. You need to run them outside the <script>
tag in the PHP:
add_action(
'wp_footer',
function () {
if ( is_archive() || is_category() || is_author() || is_date() ) {
?>
<script>
// etc.
</script>
<?php
}
}
);
You were also missing the ()
on is_archive
.