Wordpress ACF:复杂的搜索需要太长时间



在我正在构建的wordpress网站中,我有一个自定义帖子(cp_course(,其中包含以下子字段:course_codecourse_durationperiod_a_startperiod_a_endperiod_b_startperiod_b_endperiod_c_startperiod_c_endperiod_d_startperiod_d_end

搜索表单具有以下字段:codedurationdatefromdateto。用户可以使用其中任何一个进行搜索。我只实现了用户使用所有搜索字段的情况:

if(!empty($code) && !empty($duration) && !empty($datefrom) && !empty($dateto))
{
$args = array(
'post_type'  => 'cp_course', 'numberposts' =>-1,'orderby' => 'ID', 'order' => 'ASC', 's' => $searchterm,
'meta_query' => 
array(
'relation' => 'AND',
array(
'key'   => 'course_code',
'value' => $code,
),
array(
'key' => 'course_duration',
'value' => $duration,
), 
array(
'relation' => 'OR',
array(
'relation' => 'AND',
array(
'key'   => 'period_a_start',
'compare' => '>=',
'type' => 'numeric',
'value' => date("Ymd", strtotime($datefrom)),
),
array(
'key'   => 'period_a_end',
'compare' => '<=',
'type' => 'numeric',
'value' => date("Ymd", strtotime($dateto)),
),
),
array(
'relation' => 'AND',
array(
'key'   => 'period_b_start',
'compare' => '>=',
'type' => 'numeric',
'value' => date("Ymd", strtotime($datefrom)),
),
array(
'key'   => 'period_b_end',
'compare' => '<=',
'type' => 'numeric',
'value' => date("Ymd", strtotime($dateto)),
),
),//IF I REMOVE the follow lines (period_c_* and period_d_*) then it works
array(
'relation' => 'AND',
array(
'key'   => 'period_c_start',
'compare' => '>=',
'type' => 'numeric',
'value' => date("Ymd", strtotime($datefrom)),
),
array(
'key'   => 'period_c_end',
'compare' => '<=',
'type' => 'numeric',
'value' => date("Ymd", strtotime($dateto)),
),
),
array(
'relation' => 'AND',
array(
'key'   => 'period_d_start',
'compare' => '>=',
'type' => 'numeric',
'value' => date("Ymd", strtotime($datefrom)),
),
array(
'key'   => 'period_d_end',
'compare' => '<=',
'type' => 'numeric',
'value' => date("Ymd", strtotime($dateto)),
),
),
),
)
);
$course = get_posts($args);
}
<div class="page_title">
<h3>Courses</h3>
</div>
<?php foreach ($course as $post):setup_postdata($post);?>
<a href="#"><?php the_title();?></a>
<?php endforeach;wp_reset_postdata();?>

但它似乎不起作用。它陷入了一个循环,已经 10 分钟了,仍在搜索。出了什么问题?

有没有比多个ifs更简单的逻辑来实现不同的情况?我将使用这样的东西,但它看起来非常长和复杂......

if(!empty($code) && !empty($duration) && !empty($datefrom) && !empty($dateto))
{....}
else if(empty($code) && !empty($duration) && !empty($datefrom) && !empty($dateto))
{....}
.......

有趣的问题,我曾经在 ACF 遇到过同样的挑战。

运行所有这些 ifs 会花费很多时间并且效率不高,我说您尝试以下方法:

在运行get_posts和启动$args之前,尝试自己构建这些元查询数组,并相应地分配它,例如:

if($code || $duration || $datefrom || $dateto){
$meta_query = array( array( 'relation' => 'AND' ) );
if ( $code ) {
array_push( $meta_query, array(
array(
'key'   => 'course_code',
'value' => $code,
)
) );
}
if($duration){
array_push( $meta_query, array(
array(
'key' => 'course_duration',
'value' => $duration,
)
) );
}
//And so on
}

对于嵌套关系(例如period_a_start(,这肯定会更具挑战性,但它非常简单,也是最简单/最有效的方法。

祝你好运!

最新更新