quarta-feira, 23 de março de 2011

[WORDPRESS] - Function para pegar posts mais lidos (most_popular_posts)

Essa função serve para pegar os posts mais lidos durante um determinado período e é possível também passar a tag de acordo com sua necessidade.

Parâmetros:
$no_posts: número de posts;
$before: tag inicial;
$after: tag final;
$show_pass_post: mostrar posts protegidos por senha;
$duration: intervalo de dias;

Function:
<?php
function most_popular_posts($no_posts = 2, $before = '<li>', $after = '</li>', $show_pass_post = false, $duration='') {
                global $wpdb;
                $request = "SELECT ID, post_title, post_content, COUNT($wpdb->comments.comment_post_ID) AS 'comment_count' FROM $wpdb->posts, $wpdb->comments";
                $request .= " WHERE comment_approved = '1' AND $wpdb->posts.ID=$wpdb->comments.comment_post_ID AND post_status = 'publish'";
                if(!$show_pass_post) $request .= " AND post_password =''";
                if($duration !="") { $request .= " AND DATE_SUB(CURDATE(),INTERVAL ".$duration." DAY) < post_date ";
                }
                $request .= " GROUP BY $wpdb->comments.comment_post_ID ORDER BY comment_count DESC LIMIT $no_posts";
                $posts = $wpdb->get_results($request);
                $output = '';
                if ($posts) {
                               foreach ($posts as $post) {
                                               $post_title = stripslashes($post->post_title);
                                               $post_content = strip_tags($post->post_content);
                                               $post_content = (strlen($post_content) > 100) ? substr(strip_tags($post->post_content),0,70)." ..." : $post_content;
                                               $comment_count = $post->comment_count;
                                               $permalink = get_permalink($post->ID);
                                               $output .= $before . '<a href="' . $permalink . '" title="' . $post_title.'">' . $post_title . '</a><br />' . $post_content . $after;
                               }
                } else {
                               $output .= $before . "None found" . $after;
                }
                echo $output;
}
?>

Chamando a função:
<?php most_popular_posts(2,"<p>","</p>"); ?>

Nenhum comentário:

Postar um comentário