douhuifen9942 2017-10-24 08:31
浏览 89
已采纳

禁用在特定Wordpress页面上执行的脚本

I want a script (already working) now running on my entire WP website, except on one specific page, the page to which referral goes.

Script that works:

<script type="text/javascript">
var d = new Date();
var day = d.getDay();

if (day == 0) {
window.location="https://example.com/mypage";
}

</script>

I try to put the following code into my functions.php:

function my_custom_script() {

if ( is_page( 'mypage' ) ) {  } 

else {

var d = new Date();
var day = d.getDay();

if (day == 0) {
window.location="https://example.com/mypage";
}

}
}
add_action( 'wp_enqueue_scripts', 'my_custom_script' );

The reason I don't want the script to run on the redirect page is because the page will than run into an endless loop.

Can anyone tell me what to do to get it working?

  • 写回答

3条回答 默认 最新

  • dongzhan1383 2017-10-24 11:00
    关注

    Unless I am missing something; all you want to do is prevent your "Sunday" mypage redirecting to itself when it is a Sunday.

    You are already checking at the client side (javascript), so rather than adding more PHP code for WP to process (on every page) it would be simpler to modify your javascript to only redirect if it is not your "Sunday" page. i.e.

    <script type="text/javascript">
      var d = new Date();
      var day = d.getDay();
    
      if (day == 0) {
        var landingPage = "https://example.com/mypage";
        var currenturl = window.location;
        if(landingPage != currenturl) {
          window.location=landingPage;
        }
      }
    </script>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?