Change Default "Search by" option from Date to Title

Was wondering if you can help with issue I am having with a Code Snippet I have created not working.

The code snippet is to change default “Sort by” option from Date to Title within all Categories.

This is the Code Snippet I am using

// Hivepress Custom Sort: Title First
add_filter( 'hivepress/v1/listings/sort_options', function( $sort_options ) {
    // Remove the Date option
    unset( $sort_options['date'] );

    // Add Title as the default sort option
    $sort_options = array( 'title' => __( 'Title', 'hivepress' ) ) + $sort_options;

    return $sort_options;
} );

Hi,

Sorry, there’s no simple code snippet for this. If you simply change the options in the dropdown list, the default order will not change anyway, you need to customize the query.

You could try this snippet:

// Change default sort order to Title
add_filter( 
 	'posts_orderby', 
 	function($orderby, $query){
  		if ( ! is_admin() && $query->get( 'post_type' ) === 'hp_listing' && is_post_type_archive('hp_listing') && $_GET['_sort'] == '' ) {
   			$orderby = 'post_title ASC';
  		}
  		return $orderby;
 	}, 
 	10, 
 	2 
);

add_filter(
	'hivepress/v1/forms/listing_sort',
	function( $form ) {
		$form['fields']['_sort']['options'][''] = 'Name';
		$form['fields']['_sort']['options']['date'] = 'Date';
		
		// Unset original sort by title to prevent duplicate
		unset($form['fields']['_sort']['options']['title']);
		
		return $form;
	},
	1000
);
1 Like

Thank you so much @GoVegan, I had almost given up on this, just noticed your snippet, used it on new site I am working on and it worked perfectly.

I’m glad to hear the snippet was helpful to you! Thanks for your feedback :slight_smile:

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.