![](/img/trans.png)
[英]filter and sort wordpress get_posts with advanced custom fields
[英]Wordpress: get_posts filter
我正在嘗試使用自定義字段在帖子中創建一些過濾器。 因此,在我的searchpage.php
中,添加了以下內容:
$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,
)
)
);
$course = get_posts($args);
但是如果我僅提供$code
或僅提供$duration
,則將不起作用,由於AND
關系,我必須同時提供它們。 有沒有比多個IFs
更簡單的方法來檢查例如是否未提供$code
然后僅按$duration
過濾帖子
編輯
通過使用ash0ur解決方案,我使用了以下代碼:
$args = array(
'post_type' => 'cp_course', 'numberposts' =>-1,'orderby' => 'ID', 'order' => 'ASC', 's' => $searchterm,
'meta_query' => array(
'relation' => 'OR',
array(
'relation' => 'AND',
array(
'key' => 'course_code',
'value' => $code,
),
array(
'key' => 'course_duration',
'value' => $duration,
),
),
array(
'key' => 'course_duration',
'value' => $duration,
),
array(
'key' => 'course_code',
'value' => $code,
)
)
);
但是,如果要擴展它以添加更多搜索詞,則會在數據庫中遇到許多INNER JOIN
查詢,這會導致服務器出現問題。 這是我嘗試過導致問題的原因:
$args = array(
'post_type' => 'cp_course', 'numberposts' =>-1,'orderby' => 'ID', 'order' => 'ASC', 's' => $searchterm,
'meta_query' => array(
'relation' => 'OR',
array(
'relation' => 'AND',
array(
'key' => 'course_code',
'value' => $code,
),
array(
'key' => 'course_duration',
'value' => $duration,
),
array(
'key' => 'course_iteration_start',
'value' => $date_from,
),
array(
'key' => 'course_iteration_end',
'value' => $date_to,
),
),
array(
'key' => 'course_duration',
'value' => $duration,
),
array(
'key' => 'course_code',
'value' => $code,
)
)
);
其中course_iteration_start
和course_iteration_end
是course_iteration
custom field
sub fields
(重復項)。
您可以使用嵌套關系:
'meta_query' => array(
'relation' => 'OR',
array(
'relation' => 'AND',
array(
'key' => 'course_code',
'value' => $code,
),
array(
'key' => 'course_duration',
'value' => $duration,
)
),
array(
'key' => 'course_duration',
'value' => $duration,
)
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.