WPSuperDealer

How to sort vehicles randomly

The Random Joy of Chaos

Once upon a time, this fella named Mike says, “How can I sort my vehicles randomly?” 

Gotta tell you, we spend a lot of time fighting random chaos and Mike is the first person to ask for this little gem, so it’s not likely to get added as a feature anytime soon. Fortunately, if you’re looking to randomize things, it’s really easy to add your own random sort by adding a little custom code.

Fear not, it’s not nearly as daunting as it sounds and we’ll walk you through the whole process.

First you need to install a fancy little PlugIn called “Code Snippets“, available for free from WordPress.org – you don’t have to use it, there’s lots of different ways to add custom code to your site, but this is the method we’ll use for our example.

After you get the “Code Snippets” PlugIn installed you’ll want to go to Dashboard->Snippets->Add New

Random Vehicles

Make your listings look fresh with every load

Name your snippet “WPSD Random Sort” and then enter the following code.

				
					function my_wpsdsort_query( $query ) {
	$query['orderby'] = 'rand';
	return $query;
}

add_filter( 'wpsd_query_filter', 'my_wpsdsort_query', 80, 1 );
				
			

Click “Only run on site front-end” then scroll down and click “Save & Activate”.

!!! BOOM - Random listings !!!

With that little piece of code active then ALL of your vehicle listings will be random.

WAIT!!! What happens if someone goes to page #2?

Well, it’ll be a random page of vehicle, which means it’s possible some of the vehicles from page #1 will also show on page #2. Such is the joy of random sorting.

Same thing with search results, they’ll be listed randomly after the first page.

This also means you can’t use the vehicle sort widget because this piece of code makes things behave randomly.

All is not lost!

We just need - MORE CODE!

Ok, so the code above isn’t perfect. But it does make our vehicles display in a random order. We just need to make some tweaks to make things a little smoother because we might not always want them to be random.

First off, we should let people decide to sort things themselves after the page loads – so let’s add the sort widget to our page and then modify the code so it doesn’t make things random if a visitor has selected their own sort option.

				
					function my_wpsdsort_query( $query ) {
    //= if there is already a sort then stop and return the current query
	if ( isset( $_GET['order_by'] ) ) {
		return $query;
	}
	$query['orderby'] = 'rand';
	return $query;
}

add_filter( 'wpsd_query_filter', 'my_wpsdsort_query', 80, 1 );
				
			

You see that fancy part where we check if an order_by is set? That tells the code that if it sees an existing sort then don’t go any further and just return what we have.

If no sort is seen then it slips past that part and we set it to ‘rand’, which is the WordPress value needed to make it random. Serious, it was already built in just like that.

You’ll notice the top part looks for order_by and the $query looks for orderby – that’s not a mistake, it’s really supposed to be that way. Strange but true.

Now that cleans things up if a sort is being performed, but what about searching? Well we need to expand that if statement and look for all the different fields we have available for searching. This is going to be different for everyone based on how you set up your search, but let’s go with the default and if you’ve done something different you’ll need to make changes as needed.

				
					function my_wpsdsort_query( $query ) {
    $fields = array(
        'order_by',
        'vehicle_year_min',
        'vehicle_year_max',
        'model',
        'price_min',
        'price_max',
        'body_style',
        'mileage_min',
        'mileage_max',
    );
    foreach( $fields as $field ) {
        //= check each field
        //= if there is a match then stop and return the current query
        if ( isset( $_GET[ $field ] ) ) {
            return $query;
        }
    }
	$query['orderby'] = 'rand';
	return $query;
}

add_filter( 'wpsd_query_filter', 'my_wpsdsort_query', 80, 1 );
				
			

In the above code we create an array of fields. This includes all of our search fields and the notorious ‘order_by’ field used for sorting.

We loop through each of those fields and see if any of them have been sent, if they have then we stop right there and return the current query. If none of them are found then we set the ‘orderby’ in the query to ‘rand’ and return it.

Let people choose random

Power to the people!

So far all of this code takes place behind the scenes. Nobody has any choice in the matter, it is what is. But it doesn’t need to be that way. WPSuperDealer has a hook that let’s us slip our own option into the sort form.

Sneaky stuff, but think of it as one of the hidden Super Powers you didn’t know you had.

				
					function my_wpsdsort_filters( $sort_items ) {
	 $sort_items['rand'] = array(
            'field_name' => '_random',
            'label' => 'Random',
            'label_asc' => 'Random',
        );
	return $sort_items;
}
add_filter( 'wpsdsort_filters', 'my_wpsdsort_filters', 10, 1 );
				
			

We add a filter for wpsdsort_filters and we add ‘rand’ as an option. If you add this under your existing code snippet and then refresh your vehicle listings you should see ‘Random’ as a sort option.

Don’t get too excited. This just adds it to the form, you still need to add some code to your other filter to make sure things are random when this gets selected.

Add this to the beginning of that first filter you made and it’ll make sure that if someone selects ‘Random’ from the sort field then they get random results.

				
					    //= if someone has explicitly selected a random search then set it and return it
    if ( isset( $_GET['order_by'] ) && '_random' == $_GET['order_by'] ) {
        $query['orderby'] = 'rand';
        return $query;
    }
				
			

One last piece to the puzzle

We have our vehicle results sorting randomly by default. We’ve also added ‘Random’ as an option to our form. But when the page loads ‘Random’ isn’t selected even though the results are random. How do we fix this?

In our first filter, right near the end, we need to tell WPSuperDealer that ‘Random’ has been selected, then we need to tell it that it was sorted “ascended” so it knows what label to use.

Here’s what the end of the filter would like:

				
						$_GET['order_by'] = '_random';
    $_GET['order_by_dir'] = 'asc';
    $query['orderby'] = 'rand';
    return $query;
				
			

Put it all together

Don’t you hate those articles with all the code, but they never put it all together so you know what goes where?

We do too, so we’re going to drop the complete snippet here at the end.

To recap, this snippet will randomly sort all your vehicles by default. It will add ‘Random’ as a sort option. If a user selects another sort then the random code will be ignored. Cross your fingers & Good Luck!

				
					function my_wpsdsort_query( $query ) {
    //= if someone has explicitly selected a random search then set it and return it
    if ( isset( $_GET['order_by'] ) && '_random' == $_GET['order_by'] ) {
        $query['orderby'] = 'rand';
        return $query;
    }
    $fields = array(
        'order_by',
        'vehicle_year_min',
        'vehicle_year_max',
        'model',
        'price_min',
        'price_max',
        'body_style',
        'mileage_min',
        'mileage_max',
    );
    foreach( $fields as $field ) {
        //= check each field
        //= if there is a match then stop and return the current query
        if ( isset( $_GET[ $field ] ) ) {
            return $query;
        }
    }
	$_GET['order_by'] = '_random';
    $_GET['order_by_dir'] = 'asc';
    $query['orderby'] = 'rand';
    return $query;
}

add_filter( 'wpsd_query_filter', 'my_wpsdsort_query', 80, 1 );

function my_wpsdsort_filters( $sort_items ) {
	 $sort_items['rand'] = array(
            'field_name' => '_random',
            'label' => 'Random',
            'label_asc' => 'Random',
        );
	return $sort_items;
}
add_filter( 'wpsdsort_filters', 'my_wpsdsort_filters', 10, 1 );
				
			

Wanna be our hero?

We’re just a loose collection of sidekicks, trying to make our way in this crazy world. We rely on support like yours to afford masks, capes and utility belts. With your support we might even be able to someday buy our own Super Vehicles – learn more here.

"Another definition of a hero is someone who is concerned about other people's well-being, and will go out of his or her way to help them -- even if there is no chance of a reward. That person who helps others simply because it should or must be done, and because it is the right thing to do, is indeed without a doubt, a real superhero." - Stan Lee​

Questions?

Send us a message

Built by the Heroes at

WPSuperTeam.com

Unleash your Hidden Hero!