下面是一个使用标记和类别过滤器创建搜索表单的方法。对于筛选帖子,此表单使用默认的文本输入方式,用户可以在其中键入一些与帖子标题和内容匹配的搜索短语。
1) 添加到主题的功能中。php
function get_tag_ids_and_names() {
$out = array();
$arga = array(
// check https://codex.wordpress.org/Function_Reference/get_tags for available params
);
$terms = get_tags( $arga );
if ( $terms ) {
foreach ( $terms as $term ) {
$out[$term->term_id] = $term->name;
}
}
return $out;
}
function get_category_ids_and_names() {
$out = array();
$arga = array(
// check https://developer.wordpress.org/reference/functions/get_categories/ for available params
);
$terms = get_categories( $arga );
if ( $terms ) {
foreach ( $terms as $term ) {
$out[$term->term_id] = $term->name;
}
}
return $out;
}
function render_select_options( array $options ) {
if ( $options ) {
foreach ( $options as $value => $name ) {
printf(
\'<option value="%s">%s</option>\',
esc_attr( $value ),
esc_html( $name )
);
}
}
}
/**
* Custom tempalte function that renders a search form
* text input for searching posts by search phrase, searches by title and content by default
* optional dropdown select filter for post tag
* optional dropdown select filter for category
* searches only posts with post post_type
*/
function search_form_with_fitlers() {
$tags = get_tag_ids_and_names();
$categories = get_category_ids_and_names();
printf(
\'<form id="search-with-filters" method="GET" action="%s">
<input type="text" name="s" value="%s">
<select name="post_tag"><option value="">--</option>%s</select>
<select name="category"><option value="">--</option>%s</select>
<input type="hidden" name="post_type" value="post">
<input type="submit" value="%s">
</form>\',
home_url( \'/\' ),
get_search_query(),
render_select_options( $tags ),
render_select_options( $categories ),
esc_html__( \'Search\', \'text-domain\' )
);
}
你也可以在
search_form_with_fitlers
在您的
searchform.php
文件
2) 在帖子/页面模板中或需要时使用
<?php search_form_with_fitlers(); ?>
另外,如果你还没有搜索或开始学习PHP,你可以在网上找到许多很好的入门教程和课程。PHP手册还介绍了该语言,
https://www.php.net/manual/en/getting-started.php, 你可以看看。