0

I know we can easily sort WP search results by appending &orderby=post_date&order=desc to the search URL like this:

https://www.example.com/s=search+terms&orderby=post_date&order=desc

How do I implement this natively to search form code I am using:

<form method="get" action="https://www.example.com/" id="sv2"><input name="s" id="s" size="30" title="Search example.com" type="search" placeholder="Search example.com"></form>

Pls help!

Perhaps a code for functions.php is required.

2
  • 1
    The same way the search parameter is set. You just need an <input> (or <select>) with name="orderby" or name="order" and a value or options set to the parameter values you need. If the parameters aren't selectable by the user then just use a hidden input. Note that this is all HTML form behaviour, and nothing to do with WordPress. Commented Jul 25, 2022 at 10:02
  • Although sam221088's answer works fine but for my custom them, this worked more easily. Thanks a lot, it saved my time!
    – KA.MVP
    Commented Jul 25, 2022 at 10:52

1 Answer 1

1

@KA.MVP You can create hidden fields for 'orderby' and 'order' with default values 'post_date' and 'desc' or 'asc' in it, you can also put this form inside add_shortcode function explained below and use wherever you want to use by adding shortcode [custom_search_form]

function search_form_func()
{
    ?>
    <form method="get" action="https://www.example.com/" id="sv2">
        <input name="s" id="s" size="30" title="Search example.com" type="search" placeholder="Search example.com">
        <input type="hidden" name="orderby" value="post_date">
        <input type="hidden" name="order" value="desc">
        <input type="submit" name="submit" value="Search">
    </form>
    <?php
}
add_shortcode('custom_search_form','search_form_func');
4
  • Seems exactly what I was looking for. I know I can add this to functions.php but how do I call it on WP template like index.php?
    – KA.MVP
    Commented Jul 25, 2022 at 10:22
  • you can use do_shortcode function to implement shortcode function in your template <?php echo do_shortcode('[custom_search_form]'); ?>
    – sam221088
    Commented Jul 25, 2022 at 10:41
  • I confirm, this works completely fine! Thanks!!
    – KA.MVP
    Commented Jul 25, 2022 at 10:59
  • There’s no reason to call do_shortcode in a template. You can just use the code directly. Commented Jul 25, 2022 at 10:59

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.