WordPress中如何获取搜索表单
发布时间:2023-05-18 06:47:14
在WordPress中获取搜索表单非常简单,主要涉及到以下几个步骤:
1. 在主题中添加搜索表单
首先,打开你的WordPress主题代码,在header.php或者sidebar.php等页面模板文件中添加以下代码:
<form method="get" id="searchform" action="<?php echo esc_url( home_url( '/' ) ); ?>"> <label for="s" class="screen-reader-text"><?php _e( '搜索:', 'textdomain' ); ?></label> <input type="text" class="field" name="s" id="s" placeholder="<?php esc_attr_e( '搜索', 'textdomain' ); ?>" /> <button type="submit" class="submit" name="submit" id="searchsubmit" ><?php _e( '搜索', 'textdomain' ); ?></button> </form>
此代码将在页面上生成一个搜索表单,代码中的“textdomain”是主题的文本域,可以替换成自己主题的文本域。
2. 获取搜索结果
在搜索结果页面(search.php)中,可以使用以下代码获取搜索关键词和搜索结果:
<?php $search_query = get_search_query(); $search_results = new WP_Query( 's=' . $search_query ); ?>
这里,get_search_query()函数将获取搜索关键词并存储在$search_query变量中,然后可以使用WP_Query类获取搜索结果。查询的参数是“s”,表示使用搜索关键词来搜索文章。
3. 显示搜索结果
在搜索结果页面中,可以使用以下代码来显示搜索结果:
<?php if ( $search_results->have_posts() ) : ?> <ul> <?php while ( $search_results->have_posts() ) : $search_results->the_post(); ?> <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li> <?php endwhile; ?> </ul> <?php else : ?> <p><?php _e( '没有搜索到相关文章', 'textdomain' ); ?></p> <?php endif; ?>
在此代码中,使用have_posts()函数和the_post()函数循环获取文章,并将文章的标题和链接输出到页面中。如果没有搜索到相关文章,则输出未搜索到相关文章的提示信息。
这些就是获取WordPress搜索表单的基本步骤。根据需要,可以修改表单样式、查询参数等来满足不同的需求。
