无法从WordPress插件加载选项

时间:2017-02-20 10:29:02

标签: php wordpress datetime

所以我有这段代码:

$now = new DateTime;
$startdate = DateTime::createFromFormat('H:i', "9:00");
$stopdate = DateTime::createFromFormat('H:i', "17:00");
if ($now > $startdate && $now < $stopdate)
    return true;
return false;

假设是9:15 Uhr。为什么这会返回假?如你所见,我只想检查当前时间是否在startdate和stopdate之间。

编辑:发现错误,但不知道如何解决它:

我正在测试WordPress插件,我有这个小插件:

<?php
class OpeningHours
{
    public $options;
    private static $instance;


    public static function get() {
        if (self::$instance === null) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    public function __construct()
    {

        add_action('admin_init', array($this, 'page_init'));
        add_action('admin_menu', array($this, 'add_plugin_page'));
        self::$instance = $this;
    }
    public function isOpen()
    {
        $dow_numeric = date('w'); $dow_text = strtolower(date('l', strtotime("Sunday +{$dow_numeric} days"))); $startname = $dow_text . "start";
        $stopname = $dow_text . "stop";
            $starttime = $this->options[$startname];
            $stoptime = $this->options[$stopname];
            $now = new DateTime;
            $startdate = DateTime::createFromFormat('H:i', $starttime);
            $stopdate = DateTime::createFromFormat('H:i', $stoptime);
            if ($now > $startdate && $now < $stopdate)
                return true;
            return false;
    }

    /**
     * Add options page
     */
    public function add_plugin_page()
    {
        // This page will be under "Settings"
        add_options_page(
            'Oeffnungzeiten managen',
            'Öffnungszeiten',
            'manage_options',
            'opening-hours-settings',
            array($this, 'create_admin_page')
        );
    }


    public function create_admin_page()
    {
        // Set class property
        $this->options = get_option('oeffnungszeiten');
        ?>
        <div class="wrap">
            <h1>Öffnungszeiten anpassen</h1>
            <p>Bitte immer im Format H:i schreiben. Für dauerhaft geschlossen verwenden sie für Anfang und Ende
                0:00.</p>
            <form method="post" action="options.php">
                <?php
                // This prints out all hidden setting fields
                settings_fields('opening_hours_group');
                do_settings_sections('opening-hours-settings');
                submit_button();
                ?>
            </form>
        </div>
        <?php
    }


    public function page_init()
    {
        register_setting(
            'opening_hours_group', // Option group
            'oeffnungszeiten', // Option name
            array($this, 'sanitize') // Sanitize
        );

        add_settings_section(
            'opening_hours_section', // ID
            'Öffnungszeiten:', // Title
            array($this, 'print_section_info'), // Callback
            'opening-hours-settings' // Page
        );

        $this->addOptionsField("opening_hours_section", "monday", "Montags geöffnet von:");
        $this->addOptionsField("opening_hours_section", "tuesday", "Dienstags geöffnet von:");
        $this->addOptionsField("opening_hours_section", "wednesday", "Mittwochs geöffnet von:");
        $this->addOptionsField("opening_hours_section", "thursday", "Donnerstags geöffnet von:");
        $this->addOptionsField("opening_hours_section", "friday", "Freitags geöffnet von:");
        $this->addOptionsField("opening_hours_section", "saturday", "Samstags geöffnet von:");
        $this->addOptionsField("opening_hours_section", "sunday", "Sonntags geöffnet von:");
    }

    public function print_section_info()
    {
    }


    /**
     * Sanitize each setting field as needed
     *
     * @param array $input Contains all settings fields as array keys
     * @return - new input
     */
    public function sanitize($input)
    {
        $new_input = array();
        $new_input = OpeningHours::subsanitize($new_input, $input, "mondaystart");
        $new_input = OpeningHours::subsanitize($new_input, $input, "mondaystop");
        $new_input = OpeningHours::subsanitize($new_input, $input, "tuesdaystart");
        $new_input = OpeningHours::subsanitize($new_input, $input, "tuesdaystop");
        $new_input = OpeningHours::subsanitize($new_input, $input, "wednesdaystart");
        $new_input = OpeningHours::subsanitize($new_input, $input, "wednesdaystop");
        $new_input = OpeningHours::subsanitize($new_input, $input, "thursdaystart");
        $new_input = OpeningHours::subsanitize($new_input, $input, "thursdaystop");
        $new_input = OpeningHours::subsanitize($new_input, $input, "fridaystart");
        $new_input = OpeningHours::subsanitize($new_input, $input, "fridaystop");
        $new_input = OpeningHours::subsanitize($new_input, $input, "fridaystop");
        $new_input = OpeningHours::subsanitize($new_input, $input, "saturdaystart");
        $new_input = OpeningHours::subsanitize($new_input, $input, "saturdaystop");
        $new_input = OpeningHours::subsanitize($new_input, $input, "sundaystart");
        $new_input = OpeningHours::subsanitize($new_input, $input, "sundaystop");
        return $new_input;
    }

    public static function subsanitize($new_input, $input, $name)
    {
        if (isset($input[$name]))
            $new_input[$name] = sanitize_text_field($input[$name]);
        return $new_input;
    }

    public function addOptionsField($section_id, $name, $title)
    {
        add_settings_field(
            $name, // ID
            $title, // Title
            array($this, 'day_callback'), // Callback
            'opening-hours-settings', // Page
            $section_id,
            array(
                'name' => $name
            )// Section
        );
    }

    /**
     * Callback to register the several functions.
     * @param $name - The name of the callback
     */
    public function day_callback($args)
    {
        $name = $args['name'];
        $namestart = $name . "start";
        $namestop = $name . "stop";
        printf(
            '<input type="text" id="%sstart" name="oeffnungszeiten[%s]" value="%s" /> Uhr bis <input type="text" id="%s" name="oeffnungszeiten[%s]" value="%s" /> Uhr',
            $namestart, $namestart, isset($this->options[$namestart]) ? esc_attr($this->options[$namestart]) : '',
            $namestop, $namestop, isset($this->options[$namestop]) ? esc_attr($this->options[$namestop]) : ''
        );
    }
}

$hours = new OpeningHours();

add_shortcode('openinghours', 'opening');
function opening($atts)
{
    ob_start();
    ?>
    <div class="wrap">
    <p style="color:<?php echo OpeningHours::get()->isOpen() ? '#006400' : '#EE3B3B' ?>"><?php echo OpeningHours::get()->isOpen() ? "Jetzt geöffnet!" : "Gerade geschlossen."  ?></p>
    </div>
    <?php
    $output = ob_get_contents();
    ob_end_clean();

    return $output;
}

罪魁祸首是:

 $this->options = get_option('oeffnungszeiten');

选项仍为NULL。所以很正常,比较是不可能的。

好像我的插件似乎无法找到选项?我找不到错误,所以你可能有一个想法。我不习惯PHP。

2 个答案:

答案 0 :(得分:0)

你的问题是时区。

检查您运行脚本的服务器是否正在使用您期望的时区。

请参阅以下内容以获取证据:

function test(DateTimeZone $timezone = null)
{
    $now = new DateTime('now', $timezone);
    $startdate = DateTime::createFromFormat('H:i', "9:00", $timezone);
    $stopdate = DateTime::createFromFormat('H:i', "17:00", $timezone);
    if ($now > $startdate && $now < $stopdate)
        return true;
    return false;
}

var_dump(test(new DateTimeZone('US/Pacific'))); // false
var_dump(test(new DateTimeZone('Europe/London'))); // true

如果您希望更改PHP使用的默认时区,请参阅date_default_timezone_set

答案 1 :(得分:-1)

这是因为$ now引用了DateTime对象。 DateTime对象还包含timezone和timezone_type。

首先,您需要从该对象的日期属性创建一个字符串。

$now = new DateTime;
$now = $now->format('H:i');
$startdate = DateTime::createFromFormat('H:i', "9:00");
$stopdate = DateTime::createFromFormat('H:i', "17:00");

if ($now > $startdate && $now < $stopdate)
    echo 'Not between start and stop';
echo 'Between start and stop';

这应该有效:)

编辑:这可能是因为您的PHP版本不起作用。我自己尝试了你的代码,它对我有用。自5.2.2以来,允许在PHP中进行直接DateTime比较。

您可以运行php -v来检查您的PHP版本。