Change order of listings to random

Hi there!

I already asked this question before but it’s been closed due to expiration.

I want to display listings in a random order, instead of date eg. For example they choose a tag, than it should randomly display all listings with that tag. If they select a category, than it displays all listings from the selected category in random order.

You said it might be possible to customizations.

I found this snipped here which works for normal blog posts:

add_action('pre_get_posts','alter_query');
function alter_query($query){
    if ($query->is_main_query() &&  is_home())
        $query->set('orderby', 'rand'); //Set the order to random
}

Could you please help me adjust this code to make it work for posts please?

Thank you.

Yes, you can try the same snippet but with this condition:

if(!is_admin() && hivepress()->router->get_current_route_name()==='listings_view_page') {
//...
}

Then it’ll be applied to any listing search or category pages.

Cannot make it work unfortunately.

Should it be in the end like:

add_action('pre_get_posts','alter_query');
function alter_query($query){
    if(!is_admin() && hivepress()->router->get_current_route_name()==='listings_view_page') {
//...
}

This doesn’t work for me.

Sorry for the delayed answer. Please try this PHP snippet. It sets random order for listing on the Listings page

add_action(
	'pre_get_posts',
	function($query){
		if(!is_admin() && 'hp_listing' === $query->get('post_type') && 'listings_view_page' === hivepress()->router->get_current_route_name()) {
			$query->set('orderby', 'rand');
		}
	},
	1000
);
2 Likes

Thank you.

Is it possible to make it work for shortcodes as well?

I added the following shortcode to my page:

[hivepress_listings columns="4" number="12" category="36"]

It still shows the same listings no matter how often I refresh the page. Is it possible to make the random order work for shortcodes as well?

As a result with my specific shortcode it should choose 12 random listings out of all listings that have the category with id 36. But it should work for every shortcode no matter the category id or even when I don’t add a category at all.

Could you please provide me a code that works for this scenario as well?

Thank you for your help and efforts. Appreciate it.

Sorry, there’s no simple code snippet for this, it would require a custom implementation. If customizations beyond the available features are required for your site, please consider hiring someone for custom work https://fvrr.co/32e7LvY

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