Jump to content

How to sort search result by date


Sergei-78

Recommended Posts

Please could you help me to sort out the search result? I need to sort it by date and the latest post should be at the top.

<?php if ( have_posts() ): ?>
<h2 style="font-weight:normal!important">Search Results for '<?php echo get_search_query(); ?>'</h2> 
<ol style="list-style:none!important;">
<?php while ( have_posts() ) : the_post(); ?>
<li>
<article>
<h2><a href="<?php esc_url( the_permalink() ); ?>" title="Permalink to <?php the_title(); ?>" rel="bookmark"><?php the_title(); ?></a></h2>
<time datetime="<?php the_time( 'Y-m-d' ); ?>" pubdate><?php the_date(); ?> <?php the_time(); ?></time> <?php comments_popup_link('Leave a Comment', '1 Comment', '% Comments'); ?>
<?php the_content(); ?>
</article>
</li>
<?php endwhile; ?>
</ol>
<?php else: ?>
<h2>No results found for '<?php echo get_search_query(); ?>'</h2>
<?php endif; ?>
Link to comment
Share on other sites

Your code is spaghetti and thus very hard to read, let alone interpret. Where is the actual query that produces the results that you want to sort differently? Have you tried altering the 'order by' clause of your select statement?

 

You should really learn to structure your script so as to place the logic (php) at the top and produce php vars of dynamic data and then place those vars into a cohesive block of html code at the bottom. Makes for better maintenance and readability. That way you can write cleaner lines without going in & out of hph mode all the time.

 

One should also write code one statement at a time and not consolidate things into single lines. Again - readability.

Link to comment
Share on other sites

Try the posts_orderby hook to alter the ORDER BY clause of the main query. More information here. You'll want to use is_search() to make sure you're dealing with the search query only.

 

ginerjm, unfortunately this is the standard way of writing a template for WordPress. There are other ways out there (one of my favorites - Timber - allows the use of Twig templates), but they're non-standard and all depend on either a plugin or specific theme.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.