Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save propertyhive/36b3dbe20440701b505923dbc0aee9ef to your computer and use it in GitHub Desktop.
Save propertyhive/36b3dbe20440701b505923dbc0aee9ef to your computer and use it in GitHub Desktop.
/*
* Random display of properties option
*/
add_filter('propertyhive_default_search_results_orderby', 'change_default_order');
function change_default_order($orderby)
{
return 'rand';
}
add_filter('propertyhive_results_orderby', 'add_random_to_sort_dropdown');
function add_random_to_sort_dropdown($options)
{
$options['rand'] = 'Random';
return $options;
}
add_filter('propertyhive_get_search_results_ordering_args', 'set_to_random_order');
function set_to_random_order($args)
{
if (isset($_GET['orderby']) && $_GET['orderby'] === 'rand') {
$args['orderby'] = 'rand';
$args['meta_key'] = '';
}
return $args;
}
function wpb_seeded_random_order($orderby_statement, $query)
{
if ( is_admin() )
{
return $orderby_statement;
}
if ( !$query->is_main_query() )
{
return $orderby_statement;
}
if ( !is_post_type_archive('property') )
{
return $orderby_statement;
}
if ( isset($_GET['orderby']) && $_GET['orderby'] != 'rand' )
{
// ordering by something else
return $orderby_statement;
}
$seed = isset($_GET['rand_seed']) ? sanitize_text_field(intval($_GET['rand_seed'])) : rand(1, 999999);
$_GET['rand_seed'] = $seed;
return "RAND($seed)";
}
add_filter('posts_orderby', 'wpb_seeded_random_order', 10, 2);
add_filter('get_pagenum_link', 'preserve_rand_seed_in_pagination_links');
function preserve_rand_seed_in_pagination_links($link)
{
if ( is_admin() )
{
return $link;
}
if ( !is_post_type_archive('property') )
{
return $link;
}
if ( isset($_GET['orderby']) && $_GET['orderby'] != 'rand' )
{
// ordering by something else
return $link;
}
$rand_seed = isset($_GET['rand_seed']) ? intval($_GET['rand_seed']) : rand(1, 999999);
// Add rand_seed to link
$link = add_query_arg([
//'orderby' => 'rand',
'rand_seed' => $rand_seed,
], $link);
return $link;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment