不準別人網(wǎng)站做反鏈好網(wǎng)站制作公司
要為WordPress添加自定義字段的篩選功能,你需要使用WordPress的查詢參數(shù)(query parameters)和WP_Query類來構建自定義查詢。以下是一個詳細的示例代碼,展示了如何添加自定義字段的篩選功能。
首先,你需要在你的主題或插件的functions.php文件中添加一個函數(shù),用于處理自定義字段的篩選請求。
function custom_field_filter() {// 檢查是否有自定義字段的篩選參數(shù)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' => '=', // 可以根據(jù)需要修改為其他比較運算符,如'LIKE');// 使用WP_Query類構建查詢$custom_query = new WP_Query($args);// 檢查是否有查詢結果if ($custom_query->have_posts()) {// 開始循環(huán)輸出文章while ($custom_query->have_posts()) {$custom_query->the_post();// 在這里輸出你的文章內(nèi)容,比如使用the_title()輸出標題,the_content()輸出內(nèi)容等the_title();the_content();// 其他你需要的輸出邏輯}// 恢復原始查詢和循環(huán)wp_reset_postdata();} else {// 沒有匹配的文章時的處理echo '沒有匹配的文章';}// 結束查詢wp_reset_query();// 停止主查詢的執(zhí)行,因為我們已經(jīng)處理了自己的查詢exit;}
}// 添加鉤子,在WordPress初始化時調(diào)用自定義字段篩選函數(shù)
add_action('init', 'custom_field_filter');
接下來,在你的模板文件中(比如archive.php或index.php),你需要添加一個篩選表單。這個表單將允許用戶輸入自定義字段的鍵和值,并觸發(fā)篩選請求。
<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><!-- 接下來的代碼是你的文章列表或其他內(nèi)容 -->
這段代碼創(chuàng)建了一個簡單的篩選表單,用戶可以在其中輸入自定義字段的鍵和值,然后點擊“篩選”按鈕來提交表單。表單的action屬性被設置為空字符串,這意味著它將提交到當前頁面,并且method屬性被設置為get,以便通過URL參數(shù)傳遞篩選值。
當用戶填寫表單并提交時,WordPress會接收到custom_field_key和custom_field_value這兩個參數(shù),并觸發(fā)init鉤子。我們的custom_field_filter函數(shù)會檢查這些參數(shù)是否存在,如果存在,則使用它們來構建自定義查詢,并顯示匹配的文章。
原文
https://www.wowsoho.com/news/6248.html