WordPress搜索功能的制作

首先要创建一个搜索表单,示例代码如下:

<form method="get" action="" onsubmit="return checkForm();">
    <input type="text" placeholder="搜索" name="s" value="<?php the_search_query(); ?>">
    <button type="submit">
        <i class="iconfont icon-sousuo"></i>
    </button>
</form>

表单要注意的是,搜索关键词输入框的name一定要为s,不然wordpress识别不了,也就进不了search.php模板页面。

这样,在点击搜索按钮后,wordpress就会自动跳转到search.php模板页面。

search.php主要代码参考:

<div class="met-news-list" m-id="noset">
    <ul class="ulstyle met-pager-ajax imagesize" data-scale="400x400">
        <?php
        $paged = 1;
        if (get_query_var('page')) {
            $paged = get_query_var('page');
        }
        $s = get_search_query();
        $args = array(
            's' => $s,
            'paged' => $paged,
            'posts_per_page' => 20
        );

        // The Query
        $the_query = new WP_Query($args);
        if ($the_query->have_posts()) {
            while ($the_query->have_posts()) {
                $the_query->the_post();
        ?>
                <li>
                    <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
                </li>

                <li class="media media-lg border-bottom1">
                    <div class="media-left">
                        <a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>">
                            <img class="media-object" src="<?php echo catch_that_image(); ?>" alt="<?php the_title(); ?>" height="100" />
                        </a>
                    </div>
                    <div class="media-body">
                        <h4> <a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>" target="_self"><?php the_title(); ?></a> </h4>
                    </div>
                </li>

            <?php
            }
        } else {
            ?>
            <!--未找到任何搜索结果-->

        <?php }
        ?>
    </ul>
    <div class="m-t-20 text-xs-center hidden-sm-down" m-type="nosysdata">
        共<strong><?php echo $the_query->max_num_pages; ?></strong>页 <strong><?php echo $wp_query->found_posts; ?></strong>条
    </div>
    <?php bootstrap_pagination($the_query); ?>
</div>

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注