wordpress后台增加浏览量,点赞数和缩略图
- 2019-03-16 18:08:17
- 2,788 次阅读
- 13
wordpress默认的后台功能比较弱,有很多地方需要我们自己增加新的功能,比如在用户管理后台文章列表位置之后要显示文章的浏览量及点赞数或者缩略图等,以达到可视化,方便用户观察,或者说哪些文章比较受欢迎,我们好心里有个底。这时,我们可以在functions文件里加入一些代码,以达到我们的需求,具体过程如下。
(1)对数字格式化
function num2tring($num) { if ($num >= 10000) { $num = round($num / 10000 * 100) / 100 .' w'; // 以万为单位 } elseif($num >= 1000) { $num = round($num / 1000 * 100) / 100 . ' k'; // 以千为单位 } else { $num = $num; } return $num; }
(2)在后台文章列表增加2列数据,以展示浏览量和点赞数
add_filter( 'manage_posts_columns', 'star_customer_posts_columns' ); function star_customer_posts_columns( $columns ) { $columns['views'] = '浏览量'; $columns['likes'] = '点赞数'; return $columns; }
(3)输出浏览量和点赞数
add_action('manage_posts_custom_column', 'star_customer_columns_value', 10, 2); function star_customer_columns_value($column, $post_id){ if($column=='views'){ $count = num2tring(get_post_meta($post_id,'views',true)); // 注意views是字段名,根据你自己的来 if(!$count){ $count = 0; } echo $count; } if($column=='likes'){ $likes_count = get_post_meta($post_id,'favorite_praise',true); // 注意favorite_praise是字段名,根据你自己的来 if(!$likes_count) { $likes_count = 0; } echo $likes_count; } return; }
(4)后台文章添加缩略图
if ( !function_exists('star_AddThumbColumn') && function_exists('add_theme_support') ) { // for post and page add_theme_support('post-thumbnails', array( 'post', 'page' ) ); function star_AddThumbColumn($cols) { $cols['thumbnail'] = __('Thumbnail'); return $cols; } function star_AddThumbValue($column_name, $post_id) { $width = (int) 40; $height = (int) 40; if ( 'thumbnail' == $column_name ) { // thumbnail of WP 2.9 $thumbnail_id = get_post_meta( $post_id, '_thumbnail_id', true ); // image from gallery $attachments = get_children( array('post_parent' => $post_id, 'post_type' => 'attachment', 'post_mime_type' => 'image') ); if ($thumbnail_id) $thumb = wp_get_attachment_image( $thumbnail_id, array($width, $height), true ); elseif ($attachments) { foreach ( $attachments as $attachment_id => $attachment ) { $thumb = wp_get_attachment_image( $attachment_id, array($width, $height), true ); } } if ( isset($thumb) && $thumb ) { echo $thumb; } else { echo __('None'); } } } // for posts add_filter( 'manage_posts_columns', 'star_AddThumbColumn' ); add_action( 'manage_posts_custom_column', 'star_AddThumbValue', 10, 2 ); // for pages add_filter( 'manage_pages_columns', 'star_AddThumbColumn' ); add_action( 'manage_pages_custom_column', 'star_AddThumbValue', 10, 2 ); }
文章评论 (0)