【问题标题】:Wordpress post grid sort by custom field only when it has value仅当它具有值时,Wordpress 后网格才按自定义字段排序
【发布时间】:2022-11-12 19:35:19
【问题描述】:

我有一个名为“按日期排序”的帖子的自定义字段。我希望能够按创建后日期对我的自定义网格进行排序除非这个自定义的“按日期排序”字段有一个值......换句话说,如果自定义字段有一个值,我希望 wordpress 采用该日期并将其用于排序目的。

现在我将我的变量定义为

$fields['customDate'] = get_field('updated_date', $post->ID);
    
    if (!empty($fields['customDate'])) {
            $fields['orderDate'] = $fields['customDate'];
        } else {
        $fields['orderDate'] = get_the_date('Ymd', $post);
    }

为了在页面上显示日期,这很好用 <?php echo date('F j, Y', strtotime($fields['orderDate']));?>

对于我的查询,我有

$posts = get_posts(array(
            'post_type' => 'post',
            'numberposts' => $numberposts,
            'tax_query' => $taxQueries,
            'post__not_in' => $exclusions,
            
            'orderby' => array(
                'orderDate' => 'DESC'
            )
            ));

但是,我确实意识到,如果我的自定义字段中没有数据库中所有其他帖子的值,这是行不通的。

有没有办法通过组合两个字段(创建日期和自定义字段)进行排序,以便如果自定义字段有值使用它进行排序,如果不使用帖子创建日期?

提前致谢!

【问题讨论】:

  • 我回答了你的问题。一般来说,以 mysql 格式保存日期并在显示时进行转换是更好的做法。可以做更好的排序等。

标签: php wordpress sorting custom-fields


【解决方案1】:

您需要获取帖子,然后自行对它们进行排序,然后通过 post__in 参数将其提供给查询

定义排序函数

function my_sort($a,$b){
    $t1 = strtotime($a['date']);
    $t2 = strtotime($b['date']);
    return $t1 - $t2;
}

获取所有帖子 ID

$post_ids = get_posts(array(
    'fields' => 'ids',
    'post_type' => 'post',
    'numberposts' => $numberposts,
    'tax_query' => $taxQueries,
    'post__not_in' => $exclusions,
));

设置数组以备后用

$get_posts = $post_ids = array();

循环遍历 id 并检查元值是否已设置并存储在新数组中

foreach($post_ids as $id){
    $updated_date = get_field('updated_date', $id);
    $date = $updated_date ? $updated_date : get_the_date('Ymd', $id);
    $get_posts[] = array('id' => $id, 'date' => $date );
}

对新的帖子数组进行排序

usort($get_posts, 'my_sort');

遍历排序后的数组并获取 id

foreach($get_posts as $p ){
    $post_ids[] = $p['id'];
}

最后从按我们的排序排序的排序数组中获取帖子

$posts = get_post(array(
    'posts_per_page' => -1,
    'post_type' => 'post',
    'post__in'  => $post_ids,
    'order' => 'DESC',
    'orderby'=> 'post__in',
));

【讨论】:

    猜你喜欢
    • 2017-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多