最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

php - Facing Problem While Running WordPress Hook For Archive, Categories, Author, Date Pages Only

programmeradmin23浏览0评论

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:

Uncaught ReferenceError: is_single is not defined

Share Improve this question asked Mar 20, 2023 at 12:51 SunnySunny 31 bronze badge
Add a comment  | 

1 Answer 1

Reset to default 0

None 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.

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论