【问题标题】:Custom sort (usort) on WP_QueryWP_Query 上的自定义排序 (usort)
【发布时间】:2020-08-08 01:31:12
【问题描述】:

环境简述:

在我的网站上,帖子应根据特定标准进行排序。该网站被翻译成不同的语言。 首先,帖子应按发布日期排序。日期存储在元字段“publication_date”中。 帖子具有元值“溢价”。如果为真,它将设置在“高级”为假的帖子上方,无论其发布日期如何。因此,优质帖子应始终排在首位,并按日期排序。 此外,仅当您使用正确的网站语言版本时,才会考虑元值“溢价”。这取决于元值“域”。这是一个可以有多个值的选择字段。 例如,如果我在网站的西班牙语版本上,所有在元值“域”中包含“西班牙”且元值“溢价”为 true 的帖子都应显示在顶部。

对于查询,我使用 Search & Filter Pro 插件 (documentation)。它已经负责按日期排序。

这是我的查询的样子:

$args = array(
    'search_filter_id' => $searchandfilter_id,
);
$ads_query = new WP_Query( $args );

// premium sort
usort( $ads_query->posts, 'premium_sort' );

/* the loop */

到目前为止,这是我的高级排序功能:(如果网站的当前语言与“域”元字段匹配,则函数check_main_and_additional_domains()返回true,否则返回false)

function premium_sort( $a, $b ) {
    $a_premium = get_post_meta( $a->ID, 'premium', true );
    $b_premium = get_post_meta( $b->ID, 'premium', true );

    if ( check_main_and_additional_domains( $a->ID ) && check_main_and_additional_domains( $b->ID ) ) {
        if ( $a_premium && $b_premium ) {
            return 0;
        }
        if ( ! $a_premium && ! $b_premium ) {
            return 0;
        }
        if ( ! $a_premium && $b_premium ) {
            return 1;
        }
        if ( $a_premium && ! $b_premium ) {
            return -1;
        }
    }

    if ( ! check_main_and_additional_domains( $a->ID ) && ! check_main_and_additional_domains( $b->ID ) ) {
        return 0;
    }

    if ( ! check_main_and_additional_domains( $a->ID ) && check_main_and_additional_domains( $b->ID ) ) {
        if ( $b_premium ) {
            return 1;
        }
    }

    if ( check_main_and_additional_domains( $a->ID ) && ! check_main_and_additional_domains( $b->ID ) ) {
        if ( $a_premium ) {
            return 1;
        }
    }
}

我无法正确排序。有时它有效,有时则无效。我不是PHP专家,所以请不要太苛刻。非常感谢您的帮助和建设性的反馈。

【问题讨论】:

    标签: php wordpress sorting usort


    【解决方案1】:

    我认为你的问题在于逻辑不一致。

    if (!check_main_and_additional_domains($a->ID) && check_main_and_additional_domains($b->ID)) {
        if ($b_premium) {
            return 1;
        }
    }
    
    if (check_main_and_additional_domains($a->ID) && !check_main_and_additional_domains($b->ID)) {
        if ($a_premium) {
            return 1;
        }
    }
    

    从上面的部分来看,对于$a_premium && ! $b_premium,您将返回-1,我认为您需要尝试将if ($a_premium) { 更改为也返回-1 而不是1。

    【讨论】:

    • 没错!现在你指出来,一切都清楚了。我显然过于关注 true 或 false 的输出,而不是注意我必须返回 1、-1 或 0 的事实
    猜你喜欢
    • 1970-01-01
    • 2018-11-28
    • 2019-08-29
    • 2013-08-12
    • 2017-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-13
    相关资源
    最近更新 更多