Skip to content

Instantly share code, notes, and snippets.

@martynchamberlin
Last active December 21, 2015 05:49
Show Gist options
  • Save martynchamberlin/6259647 to your computer and use it in GitHub Desktop.
Save martynchamberlin/6259647 to your computer and use it in GitHub Desktop.
Getting truly unique quotes with Srini G's Quotes Collection plugin for WordPress
<?php
/**
* The Quotes Collection plugin, downloadable at http://wordpress.org/plugins/quotes-collection/,
* is a great plugin. I've used it on a couple of client sites and it's simple to use.
* However, there exists one little problem. If you want to show more than one quote
* on a page, and you want those quotes to be different every time, there's no way to do
* that. Replace the quotescollection_get_quote() function in quotes-collection.php with
* my modified version below. Specifically, this guarantees that the quotes are truly random,
* and that once served on a page, you will not get the same quote again. To prove this in
* action, go to your theme's functions.php file and paste this in:
for ( $i = 0; $i < 10; $i++)
{
quotescollection_quote('show_source=true&ajax_refresh=false');
}
* This will print 10 unique quotes to the screen, assuming you have that many in WordPress.
*
* I've asked Scrini to incorporate this (or something similar) to the live repository, but
* he's never gotten back with me. I've had to write this code twice now, so I'm finally
* creating a Gist out of it. Google my name if you have trouble with it — you'll find me
* easily enough.
*/
function quotescollection_get_quote( $condition = '', $random = 1, $current = 0 )
{
static $used_ids = array();
global $wpdb;
$sql = "SELECT quote_id, quote, author, source
FROM " . $wpdb->prefix . "quotescollection";
if ( $condition )
{
$sql .= $condition;
}
if( ! $random )
{
if ( $current )
{
$sql .= " AND quote_id < {$current}";
}
$sql .= " ORDER BY quote_id DESC";
}
else
{
if ( count( $used_ids ) > 0 )
{
$sql .= ' AND quote_id !=';
for ( $i = 0; $i < count( $used_ids ); $i++ )
{
$sql .= $used_ids[ $i ] . " ";
if ( ( $i + 1 ) != count( $used_ids ) )
{
$sql .= 'AND quote_id !=';
}
}
}
$sql .= " ORDER BY RAND( " . rand() . ")";
}
$sql .= " LIMIT 1";
$random_quote = $wpdb->get_row( $sql, ARRAY_A );
array_push( $used_ids, $random_quote['quote_id'] );
if ( empty( $random_quote ) )
{
if ( ! $random && $current )
{
return quotescollection_get_quote( $condition, 0, 0 );
}
else
{
return 0;
}
}
else
{
return $random_quote;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment