Display content based on date with PHP

后端 未结 5 823
醉酒成梦
醉酒成梦 2021-01-15 10:15

I\'m putting together a contest site built on Wordpress. Legally, the contest has to start at midnight. To avoid being up at midnight to set up the content, i\'d like to bui

相关标签:
5条回答
  • 2021-01-15 10:47

    You will want to modify your WordPress theme so that the changes can be site-wide.

    1. Log in to your WordPress installation.
    2. Navigate to Appearance > Editor
    3. In the Templates section, go to header.php
    4. At the very beginning of header.php, insert your code :

    <?php
    $date = time();
    
    $contestStart = strtotime('2012-02-03 00:00:00');
    
    if ($date < $contestStart) {
    ?>
    
    <html>
        Insert your whole splash page here.
    </html>
    
    <?php
    exit;
    }
    ?>
    //The normal template code should be below here.
    

    Don't forget to click the "Update File" button on WordPress when you're done; and like the others said, make sure that your specified time is synced with whatever timezone the server is in.

    0 讨论(0)
  • 2021-01-15 10:48

    // setup the start date (in a nice legible form) using any
    // of the formats found on the following page:
    // http://www.php.net/manual/en/datetime.formats.date.php
    $contestStart = "February 1, 2012"; 
    
    // check if current time is before the specified date
    if (time() < strftime($contestStart)){
      // Display splash screen
    }
    
    // date has already passed
    else {
      // Display page
    }
    
    0 讨论(0)
  • 2021-01-15 10:51

    You don't have to wrap the content, you can have something like:

    <?php 
    
    if ( time() < strtotime('2012-02-03 00:00:00') ) {
        echo "not yet!";
        exit;
    }
    
    //code here wont be executed
    

    Be careful of timezones! Your server might be in a different timezone than your content.

    0 讨论(0)
  • 2021-01-15 10:52

    I suppose technically your code's logic would work but yes, there are much better ways of doing this. However, for your purpose we will go simple.

    You should be comparing against a timestamp and not a string. Try this:

    <?php
    
    // The current date
    $date = time();
    
    // Static contest start date
    $contestStart = strtotime('2012-02-03 00:00:00');
    
    // If current date is after contest start
    if ($date > $contestStart) {
    //contest content?
    }
    
    else {
    // splash content?
    }
    ?>
    
    0 讨论(0)
  • 2021-01-15 11:11

    You can put the splash and content components in separate .php files, and simply include() then within the conditionals.

    if ($date > $contestStart) {
        include("SECRETDIR/contest.php");
    }
    
    else {
        include("SECRETDIR/splash.php");
    }
    

    You'll want to set up an .htaccess so that people cannot point their browsers towards secretdir and directly access contest.php

    0 讨论(0)
提交回复
热议问题