如何向 buddypress 功能添加过滤器以将保存的时间从 GMT 更改为本地时间

问题描述 投票:0回答:1

我将 buddypress 与 wordpress 一起使用。日期/日期时间始终以 GMT/UTC 格式保存在数据库中,没有任何偏移。这会导致在与 NOW() 进行比较时出现计算错误以及错误的输出,因为该日期在前端显示时未修改。

这就是为什么我希望保存并显示欧洲时区的当地时间(偏移 2 小时)。不确定这是否是一个错误。 无论如何,当我在下面的 buddypress 核心函数中将 $gmt 设置为 false 时,本地时间将被保存并且一切正常。但这并不是修改核心的好方法。那么如何向该函数添加过滤器并将 $gmt 设置为 FALSE?

/**
 * Get the current GMT time to save into the DB.
 *
 * @since 1.2.6
 *
 * @param bool   $gmt  True to use GMT (rather than local) time. Default: true.
 * @param string $type See the 'type' parameter in {@link current_time()}.
 *                     Default: 'mysql'.
 * @return string Current time in 'Y-m-d h:i:s' format.
 */
function bp_core_current_time( $gmt = **true**, $type = 'mysql' ) { // set gmt to false here works

    /**
     * Filters the current GMT time to save into the DB.
     *
     * @since 1.2.6
     *
     * @param string $value Current GMT time.
     */
    return apply_filters( 'bp_core_current_time', current_time( $type, $gmt ) );
}

我的尝试:

add_filter('bp_core_current_time','current_time2');
    function current_time2 () {
    return current_time($type='mysql',$gmt=false);
}

这会导致错误“Uncaught TypeError: date(): Argument #2 ($timestamp) must be of type ?int, string给定...”

add_filter('bp_core_current_time','current_time2');
    function current_time2 ($gmt) {
    return $gmt=false;
}

这不起作用,返回时间戳并将 0000-00-00 00:00:00 保存在数据库中。

php wordpress buddypress
1个回答
0
投票

您遇到的问题是由于您尝试使用过滤器修改

bp_core_current_time()
函数的行为所致。过滤器钩子
bp_core_current_time
允许您修改函数的返回值,但到目前为止您的尝试尚未正确修改行为以强制使用当地时间而不是 GMT。以下是解决问题并正确应用过滤器的方法。

  • 更改核心行为:如果您弄乱了 BuddyPress 核心功能中的
    $gmt
    标志,它将在数据库中保存本地时间而不是 GMT。但调整核心代码并不是一个好主意,因为更新时它可能会变得混乱。
  • 过滤器的错误使用:您尝试的方法没有正确使用过滤器。过滤器希望您更改
    bp_core_current_time
    的返回值,而不仅仅是使用
    $gmt
    参数。

要更改保存时间的方式,您需要连接到

bp_core_current_time
并调整时间的处理方式,而无需直接更改 BuddyPress 核心。

// Add a filter to modify the behavior of bp_core_current_time.
add_filter('bp_core_current_time', 'override_bp_core_current_time', 10, 2);

/**
 * Custom function to override the BuddyPress core time to use local time instead of GMT.
 *
 * @param string $time The current time in GMT.
 * @param string $type The format of the time, e.g., 'mysql'.
 * @return string Modified time in the local timezone.
 */
function override_bp_core_current_time( $time, $type ) {
    // Return the local time (non-GMT) by setting $gmt to false.
    return current_time( $type, false );
}

current_time()
函数会自动处理 WordPress 时区设置,因此请确保您的 WordPress 安装配置为使用正确的时区(例如,偏移量为 2 小时的欧洲时区)。

您可以在 WordPress 管理仪表板中的设置 > 常规 > 时区下进行配置。

© www.soinside.com 2019 - 2024. All rights reserved.