[英]Wordpress Plugin Options Page Search
我正在構建一個Wordpress插件,並希望在我的選項頁面中添加一個帖子搜索字段。 我試圖使用<input type="text" name="s" id="searchform">
添加標准的WP搜索表單,但是當我單擊“提交”時,我被重定向到“常規”設置頁面。 如何在插件選項頁面中實現搜索表單,並使搜索表單將帖子列表返回到同一頁面? 如果可能,我想在沒有AJAX的情況下執行此操作。 帖子列表標記非常復雜,必須使用JS實現它並不是理想的選擇。
我還嘗試將搜索表單HTML復制到“帖子”頁面上。 這會導致相同的問題-重定向到“常規”設置頁面。
輸入文本框必須在表單內封閉。 這是默認的html5表單。 只需使用此代碼替換您的代碼,然后修復樣式。
<form role="search" method="get" class="search-form" action="<?php echo home_url( '/' ); ?>">
<label>
<span class="screen-reader-text"><?php echo _x( 'Search for:', 'label' ) ?></span>
<input type="search" class="search-field" placeholder="<?php echo esc_attr_x( 'Search …', 'placeholder' ) ?>" value="<?php echo get_search_query() ?>" name="s" title="<?php echo esc_attr_x( 'Search for:', 'label' ) ?>" />
</label>
<input type="submit" class="search-submit" value="<?php echo esc_attr_x( 'Search', 'submit button' ) ?>" />
</form>
我不想為此使用AJAX,但最終不得不這樣做。 我想出的解決方案是使用AJAX生成“重定向” URL,並使用add_query_arg()
附加查詢參數,然后返回帶有查詢參數的URL,並使用window.location.href
來重定向用戶。 使用附加的查詢參數重定向頁面,然后在頁面加載WP_Query();
與包含查詢參數的s=
參數一起運行。
可能不是最有效的方法,甚至不是正確的方法,但它可以完成工作。 如果有人有其他解決方案,我很想聽聽。
PHP函數示例:
public function user_redirect_by_search() {
$search_arr = array();
parse_str($_POST['search_data'], $search_arr);
$return = array();
$post_type_arr = array();
$post_type_count = 0;
foreach($search_arr['post_type'] as $post_type) {
$post_type_count++;
$post_type_arr[$post_type_count] = $post_type;
}
$redirect_url = add_query_arg( array('post_type' => implode(",", $post_type_arr), 'keywords' => $search_arr['s']), $search_arr['page_url']);
$return['status'] = 1;
$return['redirect_url'] = $redirect_url;
echo json_encode($return);
die();
}
然后是jQuery:
// Post keyword search
jQuery('#searchform').on('submit', function(e) {
e.preventDefault();
var search_data = jQuery(this).serialize();
jQuery.ajax({
type: "POST",
url: ajaxurl,
dataType: 'json',
data: {"action": "user_search", search_data},
success: function(data) {
if(data.status == 1) {
window.location.href = data.redirect_url;
//console.log(data);
} else {
alert("Oops, an error occurred. Please try again or contact the plugin developer.");
console.log(data);
}
}
});
});
請注意,上面的代碼並未投入生產使用,它只是為了說明手頭問題的示例解決方案而編寫/修改的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.