北极寒流 » 网络资源 » WordPress图片相关日志(免插件版) - 2011.07.01

WordPress图片相关日志(免插件版)

免插件实现WordPress图片相关文章。要实现WordPress图片相关文章,首先的的开启wordpress自带的缩略图功能。

1.开启 WordPress隐藏的缩略图功能(WordPress 2.9版本以后才支持),在 funtions.php 中加入以下代码:

if(function_exists('add_theme_support')){ //确保 WordPress 2.9 且支持缩略图的函数
add_theme_support();
add_theme_support('post-thumbnails', array('post'));
}

这时在编辑日志时,可以看到右栏的下方多了一个模块,“文章缩略图”,这里就可以上传、设置、编辑缩略图。

2.接下来就是把缩略图和相关日志结合起来。完整WordPress图片相关日志免插件版代码如下:

function wp_get_related_posts()
{
global $wpdb, $post,$table_prefix;
$limit = 6; //显示几条相关文章
if(!$post->ID){return;}
$now = current_time('mysql', 1);
$tags = wp_get_post_tags($post->ID);
$taglist = "'" . $tags[0]->term_id. "'";
$tagcount = count($tags);
if ($tagcount > 1) {
for ($i = 1; $i < $tagcount; $i++) {
$taglist = $taglist . ", '" . $tags[$i]->term_id . "'";
}
}
$limitclause = "LIMIT $limit";
$q = "SELECT p.ID, p.post_title, p.post_date,  p.comment_count, count(t_r.object_id) as cnt FROM $wpdb->term_taxonomy t_t, $wpdb->term_relationships t_r, $wpdb->posts p WHERE t_t.taxonomy ='post_tag' AND t_t.term_taxonomy_id = t_r.term_taxonomy_id AND t_r.object_id  = p.ID AND (t_t.term_id IN ($taglist)) AND p.ID != $post->ID AND p.post_status = 'publish' AND p.post_date_gmt < '$now' GROUP BY t_r.object_id ORDER BY cnt DESC, p.post_date_gmt DESC $limitclause;";
$related_posts = $wpdb->get_results($q);
$output = "";
if (!$related_posts)
{
$output .= '<li>无相关日志</li>';
}
foreach ($related_posts as $related_post )
{
if ( has_post_thumbnail($related_post->ID) ) {
$related_thumb = get_the_post_thumbnail($related_post->ID,array(50,50),array('class'=>'relatedimg'));
} else {
$related_thumb = '<img class="relatedimg" src="http://wange.im/images/adforsale.gif" />';//无缩略图时显示默认图片
}
$dateformat = get_option('date_format');
$output .= '<li>'.$related_thumb;
$output .= '<a href="'.get_permalink($related_post->ID).'" title="'.wptexturize($related_post->post_title).' ('.mysql2date($dateformat, $related_post->post_date).')">'.wptexturize($related_post->post_title).'</a> ('. $related_post->comment_count .')';
$output .= '</li>';
}
$output = '<div><h3>相关日志</h3><ul>' . $output . '</ul></div>';
return $output;
}
function wp_related_posts_attach($content)
{
if (is_single()||is_feed())
{
$output = wp_get_related_posts();
$content = $content . $output;
}
return $content;
}
add_filter('the_content', 'wp_related_posts_attach',100);

把上述代码放在functions.php 中,然后在有需要的地方调用即可。

评论关闭