0

I want to add custom query args to search.php and i made this:

<?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(); ?>

But it not working. It shows all posts.

2

You have to pass the search query too. To get the search query, you can use the get_search_query() function, and pass it to the query's s parameter:

$search_string = get_search_query();

$args = array( 
    's'              => $search_string,
    'posts_per_page' => 12,
    'order'          => 'DESC',
);
2
  • 's' => $search_query, changed to 's' => $search_string and it works now. Thank you :)
    – wpdev
    Mar 5 '18 at 21:33
  • 1
    My bad sorry. No problem :)
    – Jack Johansson
    Mar 5 '18 at 21:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.