問題描述
我想排除首頁關閉的帖子以徵求意見。這是因為這樣:Show only posts which can be commented
現在,我想新增例外的可能性 – 顯示某些留言的帖子。它們標有自定義欄位”show_always” 。
我試過了:
function wpjj_filter_sticky( $query ) {
$meta_query = array(
'relation' => 'OR',
array(
'key' => 'show_aways',
'value' => 'yes',
'compare' => 'EXISTS'
),
array (
'comment_status' => 'open'
)
);
$query->set( 'meta_query', $meta_query );
}
add_filter( 'pre_get_posts', 'wpjj_filter_sticky' );
但它只會顯示與元的帖子,而不是公開的帖子。
最佳解決方案
讓我們嘗試以下:
預設情況下,不管 comment_status 如何,都會返回所有帖子,所以可以正常執行主查詢,即查詢所有帖子,不管 comment_status 如何。
我們還將執行一個小而又非常精細的二級查詢,我們將收到所有的帖子
-
封閉的
comment_status -
它們的值不是
yes
返回的 ID 將被作為 post__not_in 傳遞給主查詢以排除這些帖子
我認為這是一個更好的方法,因為處理自己涉及元查詢的 SQL 可能會變得非常麻煩,特別是當您開始新增複雜的巢狀元查詢時。讓 WP_Query 為我們處理 meta_query 部件。
我們仍將使用您的連結問題中的 @TheDeadMedic 自定義過濾器支援的 comment_status 引數
add_action( 'pre_get_posts', function ( $q )
{
if ( $q->is_home()
&& $q->is_main_query()
) {
// Run our secondary query to get the posts to exclude
$args = [
'posts_per_page' => -1,
'comment_status' => 'closed',
'meta_query' => [
'relation' => 'OR',
[ // Compensate for posts which have the custom field set but not set to yes
'key' => 'show_always',
'value' => 'yes',
'compare' => 'NOT IN' // Get posts which value is not yes
],
[ // Compensate for posts which does not have the custom fields
'key' => 'show_always',
'compare' => 'NOT EXISTS' // Get posts which value is not yes
]
],
'fields' => 'ids', // Return only post ID's
'suppress_filters' => false, // Allow the comment_status filter
// Any other parameters
];
$exclude_ids = get_posts( $args );
// Now we can exclude the ID's we just queried
$q->set( 'post__not_in', $exclude_ids );
}
});
EDIT
以上程式碼現在已經按預期進行了測試和工作
編輯來自評論
@birgire 已經提交了一張新的 trac 票證 (trac ticket #35601) 來詢問為什麼 comment_status 預設不能用於 WP_Query 。希望我們能夠在不久的將來將其納入核心。一旦發生這種情況,就不再需要自定義過濾器了
參考文獻
注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。