从时间戳中筛选星期几

时间:2017-08-04 作者:Drakes

我试图在管理编辑区域中按星期几(1=周一,2=周二等)过滤帖子的显示。自定义字段“some date”是一个时间戳。下面的代码并不是实现这一点的正确方法,但说明了我正在努力实现的目标。

// Filter on day of week
add_filter( \'parse_query\', array( &$this, \'dayFilter\' ), 10);

// Filter the query on the day of the week held by custom timestamp field \'some-date\'
public function dayFilter( $query )
{
    // Essential code below

    $qv = &$query->query_vars;
    $qv[\'meta_query\'] = [];

    // Filter on the day of week
    if ( !empty( $_GET[\'filter_day_of_Week\'] ) )
    {
        $day = intval( $_GET[\'filter_day_of_Week\'], 10 );
        $qv[\'meta_query\'][] = array(
            \'key\' => \'WEEKDAY(FROM_UNIXTIME(wpcf-some-date))\',
            \'value\' => $day,
            \'compare\' => \'IS\'
        );
        $sort_key = \'wpcf-some-date\';
    }
}
不是在这里,而是我需要去的地方WEEKDAY(FROM_UNIXTIME(wpcf-some-date)) 进入请求SQL。我考虑过在posts_request 过滤器挂钩,但如果有人有更好的建议,我将不胜感激。

1 个回复
最合适的回答,由SO网友:Drakes 整理而成

这个答案可能会帮助那些真正想定制过滤器的人。通过PhpStorm和断点,我可以了解meta_query 在获取帖子之前构造。流中没有让开发人员完成这一任务的挂钩点;我使用了SQL注入技巧来实现过滤器。

// Do advanced SQL editing for filtering the days of the week
add_filter( \'posts_where_request\', array( &$this, \'processSQLDelMarkers\' ), 99, 2 );

/**
 * Manipulate the pre-flight SQL query to filter on the day of the week.
 * Remove any ##DEL## marker as well as the next character after it
 * @param $where
 * @return mixed
 */
public function processSQLDelMarkers($where, \\WP_Query &$query)
{
    // Special gate
    if (stripos($where, \'##DEL##\') === false) {
        return $where;
    }

    // ... security checks omitted for brevity ...

    /**
     *  Sample where clause before adjustment:
     *  ... AND ihs_postmeta.meta_value != \'##DEL##\\\' AND WEEKDAY(FROM_UNIXTIME(ihs_postmeta.meta_value)) = 4##DEL##\' ) ...
     *  becomes
     *  ... AND ihs_postmeta.meta_value != \'\' AND WEEKDAY(FROM_UNIXTIME(ihs_postmeta.meta_value)) = 4 ) ...
     */
    return preg_replace( \'(##DEL##.?)\', \'\', $where );
}
然后使用精心构造的元value 和假人compare 这样(参见原始问题中的代码)我就可以实现SQL注入:

$qv[\'meta_query\'][] = array(
    \'key\' => \'##DEL##\\\' AND WEEKDAY(FROM_UNIXTIME(ihs_postmeta.meta_value)) = 4##DEL##\',
    \'value\' => $day,
    \'compare\' => \'!=\'
);
Note: 通过正确的安全检查,应该不可能注入不需要的SQL字符串。

结束