*
* The plugin emits a
and a .
* Each element has a class of "related", so they can be styled.
*/
function dlc_related ($count = 5, $field = 'keywords') {
global $post, $wpdb;
$keywords = get_post_custom_values('keywords');
// No keywords? Nothing is relevant.
if (count($keywords) == 0)
return;
// Get all possible keyword combinations, and sort them by
// number of keywords. This functions as relevancy, i.e.,
// the more keywords they have in common the more relevant
// the post is.
$sets = power_set($keywords);
uksort($sets, '_size_sort');
$sql = "SELECT x.post_title AS title, p.post_id FROM ";
$tables = array("{$wpdb->posts} x", "{$wpdb->postmeta} p");
$where = "
WHERE x.ID = p.post_ID
AND x.post_date <= NOW()
AND x.post_status = 'publish'
AND p.post_id != '$post->ID'
AND p.meta_key = '{$field}'";
$did_header = 0;
$seen = array();
foreach ($sets as $set) {
$nkw = count($set);
$ltables = $tables;
$lwhere = $where;
$all_kws = join(', ', $set);
// power_sets() returns an empty set
if (count($set) == 0) {
if ($did_header)
echo "
\n";
return;
}
for ($i = 0; $i <= $nkw; $i++) {
if ($set[$i]) {
array_push($ltables, "{$wpdb->postmeta} p{$i}");
$lwhere .= "
AND p.post_id = p{$i}.post_id
AND p.meta_key = p{$i}.meta_key
AND p{$i}.meta_value = '{$set[$i]}'";
}
}
$lsql = $sql . join(', ', $ltables) . $lwhere . "
GROUP BY p.post_ID
ORDER BY x.post_date DESC
LIMIT $count";
$results = $wpdb->get_results($lsql);
$good_results = 0;
if (count($results)) {
if (! $did_header) {
echo "\n";
echo "\n";
return;
}
if (! isset($seen[ $result->post_id ])) {
echo '
' . $result->title . "\n";
$seen[ $result->post_id ] = 1;
$good_results += 1;
}
}
}
#print "\n$lsql\n";
#print_r($results);
$count -= $good_results;
// exit if we've already displayed all we've been asked to.
if ($count <= 0) {
if ($did_header)
echo "\n";
return;
}
}
if ($did_header)
echo "\n";
}
/* Determines all the possible sets based on $arr,
* and returns an array of them */
function power_set ($arr) {
$sets = array();
if (!$arr) return array($arr);
foreach (power_set(array_slice($arr, 1)) as $i) {
$sets[] = $i;
$sets[] = array_merge(array($arr[0]), $i);
}
return $sets;
}
function _size_sort ($a, $b) {
return count($a) == count($b)
? 0
: count($a) >= count($b)
? 1
: -1;
}