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 Answers 2

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
    Commented Mar 5, 2018 at 21:33
  • 1
    My bad sorry. No problem :)
    – Johansson
    Commented Mar 5, 2018 at 21:34
0

How can this be done with including an orderby for first relevance and second post date desc? Would it be inserting two orderbys above the 'order' line? Any insight into this would be greatly appreciated. Sorry to revive such an old thread.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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