要為WordPress添加自定義字段的篩選功能,你需要使用WordPress的查詢參數(query parameters)和WP_Query類來構建自定義查詢。以下是一個詳細的示例代碼,展示了如何添加自定義字段的篩選功能。
首先,你需要在你的主題或插件的functions.php文件中添加一個函數,用于處理自定義字段的篩選請求。
function custom_field_filter() {
// 檢查是否有自定義字段的篩選參數
if (isset($_GET['custom_field_key']) && isset($_GET['custom_field_value'])) {
$custom_field_key = sanitize_text_field($_GET['custom_field_key']);
$custom_field_value = sanitize_text_field($_GET['custom_field_value']);
// 將自定義字段篩選條件添加到查詢變量中
$args = array(
'meta_key' => $custom_field_key,
'meta_value' => $custom_field_value,
'meta_compare' => '=', // 可以根據需要修改為其他比較運算符,如'LIKE'
);
// 使用WP_Query類構建查詢
$custom_query = new WP_Query($args);
// 檢查是否有查詢結果
if ($custom_query->have_posts()) {
// 開始循環輸出文章
while ($custom_query->have_posts()) {
$custom_query->the_post();
// 在這里輸出你的文章內容,比如使用the_title()輸出標題,the_content()輸出內容等
the_title();
the_content();
// 其他你需要的輸出邏輯
}
// 恢復原始查詢和循環
wp_reset_postdata();
} else {
// 沒有匹配的文章時的處理
echo '沒有匹配的文章';
}
// 結束查詢
wp_reset_query();
// 停止主查詢的執行,因為我們已經處理了自己的查詢
exit;
}
}
// 添加鉤子,在WordPress初始化時調用自定義字段篩選函數
add_action('init', 'custom_field_filter');
接下來,在你的模板文件中(比如archive.php或index.php),你需要添加一個篩選表單。這個表單將允許用戶輸入自定義字段的鍵和值,并觸發篩選請求。
<form method="get" action="">
<label for="custom_field_key">自定義字段鍵:</label>
<input type="text" name="custom_field_key" id="custom_field_key" value="<?php echo isset($_GET['custom_field_key']) ? $_GET['custom_field_key'] : ''; ?>">
<label for="custom_field_value">自定義字段值:</label>
<input type="text" name="custom_field_value" id="custom_field_value" value="<?php echo isset($_GET['custom_field_value']) ? $_GET['custom_field_value'] : ''; ?>">
<input type="submit" value="篩選">
</form>
<!-- 接下來的代碼是你的文章列表或其他內容 -->
這段代碼創建了一個簡單的篩選表單,用戶可以在其中輸入自定義字段的鍵和值,然后點擊“篩選”按鈕來提交表單。表單的action屬性被設置為空字符串,這意味著它將提交到當前頁面,并且method屬性被設置為get,以便通過URL參數傳遞篩選值。
當用戶填寫表單并提交時,WordPress會接收到custom_field_key和custom_field_value這兩個參數,并觸發init鉤子。我們的custom_field_filter函數會檢查這些參數是否存在,如果存在,則使用它們來構建自定義查詢,并顯示匹配的文章。