This code comes from a Wordpress plugin's forum called Vote it Up. It sort posts by vote. A lotof people say that there is more code than is needed. So I was wondering if someone have any idea about how to clean it a bit.
votingfunctions.php:
function ShowPostByVotes() {
global $wpdb, $voteiu_databasetable;
mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) or die(mysql_error());
mysql_select_db(DB_NAME) or die(mysql_error());
//Set a limit to reduce time taken for script to run
$upperlimit = get_option('voteiu_limit');
if ($upperlimit == '') {
$upperlimit = 100;
}
$lowerlimit = 0;
$votesarray = array();
$querystr = "
SELECT *
FROM $wpdb->posts
WHERE post_status = 'publish'
AND post_type = 'post'
ORDER BY post_date DESC
";
$pageposts = $wpdb->get_results($querystr, OBJECT);
//Use wordpress posts table
//For posts to be available for vote editing, they must be published posts.
mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) or die(mysql_error());
mysql_select_db(DB_NAME) or die(mysql_error());
//Sorts by date instead of ID for more accurate representation
$posttablecontents = mysql_query("SELECT ID FROM ".$wpdb->prefix."posts WHERE post_type = 'post' AND post_status = 'publish' ORDER BY post_date_gmt DESC LIMIT ".$lowerlimit.", ".$upperlimit."") or die(mysql_error());
$returnarray = array();
while ($row = mysql_fetch_array($posttablecontents)) {
$post_id = $row['ID'];
$vote_array = GetVotes($post_id, "array");
array_push($votesarray, array(GetVotes($post_id)));
}
array_multisort($votesarray, SORT_DESC, $pageposts);
$output = $pageposts;
return $output;
}
index.php:
$pageposts = ShowPostByVotes();
?>
<?php if ($pageposts): ?>
<?php foreach ($pageposts as $post): ?>
<?php setup_postdata($post); ?>
Attention! Code above is something like:
<?php if (have_posts()) : ?>
<?php while (have_posts()) : the_post(); ?>
so in foreach loop you can use statements like in standard "The Loop" for example the_content, the_time(). To end this add
<?php endforeach; ?>
<?php else : ?>
<h2 class="center">Not Found</h2>
<p class="center">Sorry, but you are looking for something that isn't here.</p>
<?php include (TEMPLATEPATH . "/searchform.php"); ?>
<?php endif; ?>
EDIT:
How I run a custom loop:
<?php $custom_posts = new WP_Query(); ?>
<?php $custom_posts->query('category_name=Pictures'); ?>
<?php while ($custom_posts->have_posts()) : $custom_posts->the_post(); ?>
<div class="content-block-2">
<a href="<?php the_permalink(); ?>" title="<?php printf( esc_attr__( 'Permalink to %s', 'twentyten' ), the_title_attribute( 'echo=0' ) ); ?>" rel="bookmark"><?php the_content(); ?></a>
</div>
<?php endwhile; ?>