搜索页面的自定义循环查询

时间:2018-03-05 作者:wpdev

我想将自定义查询参数添加到search.php 我做了这个:

<?php get_header(); ?>

    <section id="primary" class="content-area">
        <main id="main" class="site-main">

        <?php
        $args = array( 
            \'posts_per_page\' => 12,
            \'order\'          => \'DESC\',
        );

        $search_posts = new WP_Query( $args );

        if ( $search_posts->have_posts() ) : ?>

            <header class="page-header">
                <h1 class="page-title">
                    <?php printf( esc_html__( \'Search Results for: %s\', \'my-theme\' ), \'<span>\' . get_search_query() . \'</span>\' ); ?>
                </h1>
            </header>

            <?php

            while ( $search_posts->have_posts() ) : $search_posts->the_post();

                get_template_part( \'template-parts/content\', \'search\' );

            endwhile;

            the_posts_navigation();

        else :

            get_template_part( \'template-parts/content\', \'none\' );

        endif; 

        wp_reset_postdata(); ?>

        </main>
    </section>

<?php get_footer(); ?>
但它不起作用。它显示所有帖子。

1 个回复
最合适的回答,由SO网友:Johansson 整理而成

您还必须通过搜索查询。要获取搜索查询,可以使用get_search_query() 函数,并将其传递给查询的s 参数:

$search_string = get_search_query();

$args = array( 
    \'s\'              => $search_string,
    \'posts_per_page\' => 12,
    \'order\'          => \'DESC\',
);

结束