在orderby语句中对自定义字段使用abs()

时间:2018-02-06 作者:Rodrigo Butzke

我有一个自定义的帖子类型“ordered\\u post”和一些这种类型的帖子。他们有一个要显示的顺序,并且所有人都有一个自定义字段“custom\\u post\\u order”。

并且它们都使用pre\\u get\\u过滤器以正确的顺序显示在存档页面中

add_action(\'pre_get_posts\', \'custom_query_ordered_post\');
function custom_query_ordered_post($query) {
    if (!is_admin() && $query->is_main_query() && $query->is_post_type_archive(\'ordered_post\')) {
        $query->set(\'meta_key\', \'custom_post_order\');
        $query->set(\'orderby\', \'meta_value\');
        $query->set(\'order\', \'DESC\');
    }
    return $query;
}
但在单个页面中,我想显示“相对帖子”,但使用abs(meta\\u值-$current\\u post\\u order)进行排序。

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

用于执行自定义分析的自定义类

class AS_Query extends \\WP_Query {

    protected function parse_orderby($order_by) {
        $additional_allowed = array();
        $absValue = null;
        if (preg_match(\'/abs\\(([0-9]+)\\)/i\', $order_by, $matches)) {
            $absValue = $matches[1];
            $order_by = sprintf(\'abs((meta_value+0) - %s)\', intval($matches[1]));
            $additional_allowed[] = $order_by;
        }
        if (!in_array($order_by, $additional_allowed, true)) {
            $parent_orderby = parent::parse_orderby($order_by);
            if ($parent_orderby) {
                return $parent_orderby;
            }
            return false;
        }
        return $order_by;
    }

    protected function parse_order($order) {
        if (!is_string($order) || empty($order)) {
            return \'DESC\';
        }
        if (\'ABS\' == strtoupper($order)) {
            return \'\'; // to get the real closest order, this should be empty
        } else if (\'ASC\' === strtoupper($order)) {
            return \'ASC\';
        } else {
            return \'DESC\';
        }
    }
}
用法:

$order= get_field("custom_post_order");
$id = get_the_ID(); //to not show the post itself in the list
if (!empty($order)) {
    require_once get_template_directory() . "/functions/classes/class-as-query.php";
    $diretoria = new AS_Query(
        array(
            \'order\' => \'abs\', // to remove "DESC" in the query to get the abs list
            \'orderby\' => \'abs(\' . $order. \')\',
            \'meta_key\' => \'custom_post_order\',
            \'posts_per_page\' => 4, //custom list limit
            \'post__not_in\' => array($id), //to not show the post itself in the list
            \'post_type\' => \'ordered_post\'
        )
    );
}
我还没有用order\\u by数组测试它

结束