I use the upgraded awesome plugin Jetpack by WordPress.com to show the ‘Top Posts’ is the sidebar. I recently noticed that the links for these post were broken, even though I wasn’t doing anything wrong at all. I queried the plugin for top 5 posts using:
echo '<ul class="most-viewed">';
foreach ( $top_posts as $p ) {
if($p['post_id'])
echo '<li><a href="'. $p['post_permalink'] .'" title="'.
$p['post_title']. '">'. $p['post_title'] .'</a> - <strong>'. $p['views'] . '</strong> views</li>';
}
echo '</ul>';
But somehow, the value at post_permalink key was wrong. Instead of pulling out my hair, I downloaded the Jetpack plugin’s source code, opened the file stats.php and copied a few lines and now the following works awesomely well.
echo '<ul class="most-viewed">';
foreach ( $top_posts as $p ) {
if($p['post_id'] && get_post($p['post_id']))
echo '<li><a href="' . get_permalink( $p['post_id'] ) . '">' .
get_the_title( $p['post_id'] ) . '</a>', number_format_i18n( $p['views'] ) </li>';
}
echo '</ul>';
}
I hope this helps people looking for a quick fix to this problem.