gpt4 book ai didi

php - wordpress Wp_query 和日期字段的元查询问题

转载 作者:行者123 更新时间:2023-11-29 16:08:56 25 4
gpt4 key购买 nike

我已将项目作为帖子插入到我的 WordPress 数据库中。目前在我的主页上,显示了最近 3 个发布的项目。现在我的目的是我想首先显示今天到期的项目而不是上次发布的项目。

例如,今天有 2 个项目到期,主页上会显示今天到期的 2 个项目和最后发布的 1 个项目。这意味着总共将显示 3 个项目。

请检查下面的 WP_query,它仅返回最后发布的项目

$args = array('post_type' => 'ignition_product', 'posts_per_page' => $project_count, 'paged' => $paged);

$newargs = apply_filters('project_query', $args);
$wp_query = new WP_Query($newargs);

下面的查询我尝试使用元键和值,但没有运气。 “ign_fund_end”将日期存储为字符串,所以我认为这就是不比较日期的原因。我的最终目标是我上面描述的总共 3 个项目应该显示。第一个应该是今天到期,然后是上次发布之后。

$args = array(
'post_type' => 'ignition_product',
'posts_per_page' => $project_count,
'paged' => $paged,
'meta_query' => array(// WordPress has all the results, now, return only the events after today's date
array(
'key' => 'ign_fund_end', // Check the start date field
'value' => date('m/d/Y'), // Set today's date (note the similar format)
'compare' => '>=', // Return the ones greater than today's date
'type' => 'DATE' // Let WordPress know we're working with date
)
));

请检查下图以供引用。 enter image description here

任何解决方案表示赞赏。

最佳答案

由于您的自定义字段 ign_fund_end 不是 MySQL 日期兼容格式,因此这是您的 WP_Query 无法按预期方式工作的主要原因。我的建议是使用 save_post 在自定义字段中保存结束日期的时间戳,然后更改 WP_Query$args 以在该字段上工作.

这是您问题的完整解决方案:

1:将时间戳保存在自定义字段中

add_action( 'save_post', function( $post_id ) {
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return;
if ( $parent_id = wp_is_post_revision( $post_id ) ) {
$post_id = $parent_id;
}

if( isset( $_POST['ign_fund_end'] ) && !empty($_POST['ign_fund_end']) ) {
$end_date = $_POST['ign_fund_end'];
$end_date = strtotime($end_date);
update_post_meta( $post_id, '__end_date', $end_date );
}
} );

2:修改$args

$args = array(
'post_type' => 'ignition_product',
'posts_per_page' => $project_count,
'orderby' => 'meta_value_num',
'order' => 'ASC',
'meta_key' => '__end_date',
'paged' => $paged,
'meta_query' => array(// WordPress has all the results, now, return only the events after today's date
array(
'key' => '__end_date', // Check the start date field
'value' => strtotime('today'), // Set today's timestamp
'compare' => '>=', // Return the ones greater than today's date
'type' => 'NUMERIC'
)
));

关于php - wordpress Wp_query 和日期字段的元查询问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55453280/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com