wordpress二次开发技巧之functions.php篇

wordpress二次开发中对于functions.php的制作是非常多的,今天我们来分享关于wordpress二次开发技巧之functions.php的制作,希望大家可以喜欢!

下面根据需求,对各种能实现进行简单介绍。

先对functions.php文件进行介绍,通过代码实现各功能。

1. widgets sidebar 侧边栏小工具

wordpress二次开发技巧之functions.php篇

01/** widgets sidebar 侧边栏小工具*/
02if( function_exists('register_sidebar'<span class="crayon-sy">) ) {
03  register_sidebar(array(
04    'name' <span class="crayon-o">=> 'First_sidebar'<span class="crayon-sy">,
05    'before_widget' <span class="crayon-o">=> ''<span class="crayon-sy">,
06    'after_widget' <span class="crayon-o">=> ''<span class="crayon-sy">,
07    'before_title' <span class="crayon-o">=> '<h4>'<span class="crayon-sy">,
08    'after_title' <span class="crayon-o">=> '</h4>'
09  ));
10  register_sidebar(array(
11    'name' <span class="crayon-o">=> 'Second_sidebar'<span class="crayon-sy">,
12    'before_widget' <span class="crayon-o">=> ''<span class="crayon-sy">,
13    'after_widget' <span class="crayon-o">=> ''<span class="crayon-sy">,
14    'before_title' <span class="crayon-o">=> '<h4>'<span class="crayon-sy">,
15    'after_title' <span class="crayon-o">=> '</h4>'
16  ));
17  register_sidebar(array(
18    'name' <span class="crayon-o">=> 'Third_sidebar'<span class="crayon-sy">,
19    'before_widget' <span class="crayon-o">=> ''<span class="crayon-sy">,
20    'after_widget' <span class="crayon-o">=> ''<span class="crayon-sy">,
21    'before_title' <span class="crayon-o">=> '<h4>'<span class="crayon-sy">,
22    'after_title' <span class="crayon-o">=> '</h4>'
23  ));
24  register_sidebar(array(
25    'name' <span class="crayon-o">=> 'Fourth_sidebar'<span class="crayon-sy">,
26    'before_widget' <span class="crayon-o">=> ''<span class="crayon-sy">,
27    'after_widget' <span class="crayon-o">=> ''<span class="crayon-sy">,
28    'before_title' <span class="crayon-o">=> '<h4>'<span class="crayon-sy">,
29    'after_title' <span class="crayon-o">=> '</h4>'
30  ));
31}
32  
33register_nav_menus(array("primary" => "Primary Navigation"));

2. 后台支持自定义菜单

wordpress二次开发技巧之functions.php篇

01/*nav  后台自定义菜单*/
02if(function_exists('register_nav_menus'<span class="crayon-sy">)){
03  register_nav_menus(
04    array(
05    'header-menu' <span class="crayon-o">=> __( '导航自定义菜单' <span class="crayon-sy">),
06    'footer-menu' <span class="crayon-o">=> __( '页角自定义菜单' <span class="crayon-sy">),
07    'sider-menu' <span class="crayon-o">=> __('侧边栏菜单'<span class="crayon-sy">),
08    'primary' <span class="crayon-o">=> __( 'Primary Navigation'<span class="crayon-sy">, 'lee' <span class="crayon-sy">),
09    )
10  );
11}

输出菜单,在如header.php插入显示菜单的代码

1<?php wp_nav_menu( array'container' <span class="crayon-o">=> '' <span class="crayon-sy">) ); ?>

3. 面包屑导航

 

01// 面包屑导航注册代码
02function wheatv_breadcrumbs() {
03  $delimiter '<i>></i>'<span class="crayon-sy">;
04  $name '首页'<span class="crayon-sy">; //text for the 'Home' link
05  $currentBefore ''<span class="crayon-sy">;
06  $currentAfter ''<span class="crayon-sy">;
07  
08  if ( !is_home() && !is_front_page() || is_paged() ) {
09  
10  echo ''<span class="crayon-sy">;
11  global $post;
12  // $home = get_bloginfo('url');
13  $home = get_option('home'<span class="crayon-sy">);
14  echo '<a href="'<span class="crayon-sy">.$home.'" >'<span class="crayon-sy">. $name ' </a>' <span class="crayon-sy">. $delimiter ' '<span class="crayon-sy">;
15  
16  if ( is_category() ) {
17    global $wp_query;
18    $cat_obj $wp_query->get_queried_object();
19    $thisCat $cat_obj->term_id;
20    $thisCat = get_category($thisCat);
21    $parentCat = get_category($thisCat->parent);
22    if ($thisCat->parent != 0) echo(get_category_parents($parentCat, TRUE, ' ' <span class="crayon-sy">. $delimiter ' '<span class="crayon-sy">));
23      echo $currentBefore ''<span class="crayon-sy">;
24      single_cat_title();
25      echo '' <span class="crayon-sy">. $currentAfter;
26  
27    elseif ( is_day() ) {
28      echo '' <span class="crayon-sy">. get_the_time('Y'<span class="crayon-sy">) .' ' <span class="crayon-sy">. $delimiter ' '<span class="crayon-sy">;
29      echo '' <span class="crayon-sy">. get_the_time('F'<span class="crayon-sy">) .' ' <span class="crayon-sy">. $delimiter ' '<span class="crayon-sy">;
30      echo $currentBefore . get_the_time('d'<span class="crayon-sy">) . $currentAfter;
31  
32    elseif ( is_month() ) {
33      echo '' <span class="crayon-sy">. get_the_time('Y'<span class="crayon-sy">) .' ' <span class="crayon-sy">. $delimiter ' '<span class="crayon-sy">;
34      echo $currentBefore . get_the_time('F'<span class="crayon-sy">) . $currentAfter;
35  
36    elseif ( is_year() ) {
37      echo $currentBefore . get_the_time('Y'<span class="crayon-sy">) . $currentAfter;
38  
39    elseif ( is_single() ) {
40      $cat = get_the_category(); $cat $cat[0];
41      echo get_category_parents($cat, TRUE, ' ' <span class="crayon-sy">. $delimiter ' '<span class="crayon-sy">);
42      echo $currentBefore;
43      the_title();
44      echo $currentAfter;
45  
46    elseif ( is_page() && !$post->post_parent ) {
47      echo $currentBefore;
48      the_title();
49      echo $currentAfter;
50  
51    elseif ( is_page() && $post->post_parent ) {
52      $parent_id $post->post_parent;
53      $breadcrumbs array();
54      while ($parent_id) {
55        $page = get_page($parent_id);
56        $breadcrumbs[] = '' <span class="crayon-sy">. get_the_title($page->ID) .''<span class="crayon-sy">;
57        $parent_id $page->post_parent;
58      }
59      $breadcrumbs array_reverse($breadcrumbs);
60      foreach ($breadcrumbs as $crumbecho $crumb ' ' <span class="crayon-sy">.$delimiter ' '<span class="crayon-sy">;
61      echo $currentBefore;
62      the_title();
63      echo $currentAfter;
64  
65    elseif ( is_search() ) {
66      echo $currentBefore '搜索结果' <span class="crayon-sy">. get_search_query() . '' <span class="crayon-sy">. $currentAfter;
67  
68    elseif ( is_tag() ) {
69      echo $currentBefore '搜索标签: '<span class="crayon-sy">;
70      single_tag_title();
71      echo '' <span class="crayon-sy">. $currentAfter;
72  
73    elseif ( is_author() ) {
74      global $author;
75      $userdata = get_userdata($author);
76      echo $currentBefore 'Articles posted by ' <span class="crayon-sy">. $userdata->display_name . $currentAfter;
77  
78    elseif ( is_404() ) {
79      echo $currentBefore 'Error 404' <span class="crayon-sy">. $currentAfter;
80  }
81  
82  if ( get_query_var('paged'<span class="crayon-sy">) ) {
83    if ( is_category() || is_day() || is_month() || is_year() || is_search() || is_tag() || is_author() ) echo ' ('<span class="crayon-sy">;
84      echo __('第'<span class="crayon-sy">) . '' <span class="crayon-sy">. get_query_var('paged'<span class="crayon-sy">) . '页'<span class="crayon-sy">;
85    if ( is_category() || is_day() || is_month() || is_year() || is_search() || is_tag() || is_author() ) echo ')'<span class="crayon-sy">;
86  }
87  echo ''<span class="crayon-sy">;
88  }
89}

显示面包屑导航(category.php或single.php等)

1<?php wheatv_breadcrumbs(); ?>

4.  文章访问量(点击数)

wordpress二次开发技巧之functions.php篇

01//文章点击数
02function getPostViews($postID){
03    $count_key 'post_views_count'<span class="crayon-sy">;
04    $count = get_post_meta($postID$count_key, true);
05    if($count==''<span class="crayon-sy">){
06        delete_post_meta($postID$count_key);
07        add_post_meta($postID$count_key'0'<span class="crayon-sy">);
08        return "0";
09    }
10    return $count;
11}
12function setPostViews($postID) {
13    $count_key 'post_views_count'<span class="crayon-sy">;
14    $count = get_post_meta($postID$count_key, true);
15    if($count==''<span class="crayon-sy">){
16        $count = 0;
17        delete_post_meta($postID$count_key);
18        add_post_meta($postID$count_key'0'<span class="crayon-sy">);
19    }else{
20        $count++;
21        update_post_meta($postID$count_key$count);
22    }
23}

显示点击量(如category.php或single.php)

1<?php echo getPostViews(get_the_ID()); ?>

5. 文章中所有链接新窗口中打开

1//为文章中所有链接添加target="_blank"属性
2function autoblank($content) {
3    $content = preg_replace("/<a(.*?)>/""<a$1 target="_blank">"$content);
4    return $content;
5}
6add_filter('the_content'<span class="crayon-sy">, 'autoblank'<span class="crayon-sy">);

6. 清除wp自带无用头部信息

01//清除头部信息
02//remove_action( 'wp_head', 'wp_enqueue_scripts', 1 );
03remove_action( 'wp_head'<span class="crayon-sy">, 'feed_links'<span class="crayon-sy">, 2 );
04remove_action( 'wp_head'<span class="crayon-sy">, 'feed_links_extra'<span class="crayon-sy">, 3 );
05remove_action( 'wp_head'<span class="crayon-sy">, 'rsd_link' <span class="crayon-sy">);
06remove_action( 'wp_head'<span class="crayon-sy">, 'wlwmanifest_link' <span class="crayon-sy">);
07remove_action( 'wp_head'<span class="crayon-sy">, 'index_rel_link' <span class="crayon-sy">);
08remove_action( 'wp_head'<span class="crayon-sy">, 'parent_post_rel_link'<span class="crayon-sy">, 10, 0 );
09remove_action( 'wp_head'<span class="crayon-sy">, 'start_post_rel_link'<span class="crayon-sy">, 10, 0 );
10remove_action( 'wp_head'<span class="crayon-sy">, 'adjacent_posts_rel_link_wp_head'<span class="crayon-sy">, 10, 0 );
11//remove_action( 'wp_head', 'locale_stylesheet' );
12remove_action( 'publish_future_post'<span class="crayon-sy">, 'check_and_publish_future_post'<span class="crayon-sy">, 10, 1 );
13//remove_action( 'wp_head', 'noindex', 1 );
14//remove_action( 'wp_head', 'wp_print_styles', 8 );
15//remove_action( 'wp_head', 'wp_print_head_scripts', 9 );
16remove_action( 'wp_head'<span class="crayon-sy">, 'wp_generator' <span class="crayon-sy">);
17//remove_action( 'wp_head', 'rel_canonical' );
18remove_action( 'wp_footer'<span class="crayon-sy">, 'wp_print_footer_scripts' <spanclass="crayon-sy">);
19remove_action( 'wp_head'<span class="crayon-sy">, 'wp_shortlink_wp_head'<span class="crayon-sy">, 10, 0 );
20remove_action( 'template_redirect'<span class="crayon-sy">, 'wp_shortlink_header'<span class="crayon-sy">, 11, 0 );
21add_action('widgets_init'<span class="crayon-sy">, 'my_remove_recent_comments_style'<span class="crayon-sy">);
22function my_remove_recent_comments_style() {
23global $wp_widget_factory;
24remove_action('wp_head'<span class="crayon-sy">, array($wp_widget_factory->widgets['WP_Widget_Recent_Comments'<span class="crayon-sy">], 'recent_comments_style'<span class="crayon-sy">));
25}

7. 自动保存和文章修订功能

wordpress二次开发技巧之functions.php篇

1//自动保存和文章修订功能
2define('AUTOSAVE_INTERVAL'<span class="crayon-sy">, 120 );  // 设置自动保存间隔,单位是秒,默认60
3define('WP_POST_REVISIONS'<span class="crayon-sy">, false); // 如果不禁用自动修订,最多允许保存的版本数,3表示最多保存3个修订版

8. 彩色静态标签云

wordpress二次开发技巧之functions.php篇

01// 彩色静态标签云 Color Tag Cloud
02function colorCloud($text) {
03  $text = preg_replace_callback('|<a (.+?)>|i'<span class="crayon-sy">, 'colorCloudCallback'<span class="crayon-sy">, $text);
04  return $text;
05}
06function colorCloudCallback($matches) {
07  $text $matches[1];
08  $color dechex(rand(0,16777215));
09  $pattern '/style=('|")(.*)('|")/i'<span class="crayon-sy">;
10  $text = preg_replace($pattern"style="color:#{$color};$2;""$text);
11  return "<a $text>";
12}
13add_filter('wp_tag_cloud'<span class="crayon-sy">, 'colorCloud'<span class="crayon-sy">, 1);

输出标签

1<?php wp_tag_cloud('smallest=10&largest=14&number=32&order=RAND'<span class="crayon-sy">) ?>

9. 搜索结果关键词高亮显示

具体实现,再另写文章介绍,后续可通过搜索找到。

wordpress二次开发技巧之functions.php篇

01// 搜索结果关键词高亮显示
02function lee_set_query() {
03  $query  = attribute_escape(get_search_query());
04  if(strlen($query) > 0){
05    echo '
06      <script type="text/javascript">
07        var lee_query  = "'.$query.'";
08      </script>
09    '<span class="crayon-sy">;
10  }
11}
12function lee_init_jquery() {
13wp_enqueue_script('jquery'<span class="crayon-sy">);
14}
15add_action('init'<span class="crayon-sy">, 'lee_init_jquery'<span class="crayon-sy">);
16add_action('wp_print_scripts'<span class="crayon-sy">, 'lee_set_query'<span class="crayon-sy">);

10. 自定义登录界面

在不更改html的情况下,可通过引入样式文件,自定义登录界面。

wordpress二次开发技巧之functions.php篇

01// 自定义登录界面
02function custom_login(){
03    echo '<link rel="stylesheet" type="text/css" href="' <span class="crayon-sy">. get_bloginfo('template_directory'<span class="crayon-sy">) . '/css/login.css" />'<span class="crayon-sy">;
04}
05add_action('login_head'<span class="crayon-sy">, 'custom_login'<span class="crayon-sy">);
06  
07function login_headerurl($url) {
08    return get_bloginfo('url'<span class="crayon-sy">);
09}
10add_filter('login_headerurl'<span class="crayon-sy">, 'login_headerurl'<span class="crayon-sy">);
11  
12function login_headertitle($title){
13    return __('轩枫阁'<span class="crayon-sy">);
14}
15add_filter('login_headertitle'<span class="crayon-sy">, 'login_headertitle'<span class="crayon-sy">);

11. 获得当前文章的位置

wordpress二次开发技巧之functions.php篇

wordpress二次开发技巧之functions.php篇

01// 当前文章
02function num_Pcurrent_post() {
03  global $wpdb;
04  $postid = get_the_ID();//获取当前文章的ID
05  $getpost = get_post($postid);
06  $daysago $getpost->post_date;//获取当前文章的发布时间
07  $today gmdate('Y-m-d H:i:s'<span class="crayon-sy">, time() + 3600 * 8);//获取当前服务器的时间
08  $count_posts = wp_count_posts();
09  $num_all_posts $count_posts->publish;//总的文章数量
10  $result $wpdb->get_results("SELECT ID FROM $wpdb->posts WHERE post_date BETWEEN '$daysago' AND '$today' AND post_status='publish' AND post_type='post' ORDER BY post_date DESC ");
11  foreach ($result as $Item) {
12  $post_ID[] = $Item->ID;
13  }
14  $num_current_post count($post_ID)-1;//当前文章发布以前的文章数量总数
15  $output .= $num_current_post.'/'<span class="crayon-sy">.$num_all_posts;
16  echo $output;
17}
18function num_Ncurrent_post() {
19  global $wpdb;
20  $postid = get_the_ID();//获取当前文章的ID
21  $getpost = get_post($postid);
22  $daysago $getpost->post_date;//获取当前文章的发布时间
23  $today gmdate('Y-m-d H:i:s'<span class="crayon-sy">, time() + 3600 * 8);//获取当前服务器的时间
24  $count_posts = wp_count_posts();
25  $num_all_posts $count_posts->publish;//总的文章数量
26  $result $wpdb->get_results("SELECT ID FROM $wpdb->posts WHERE post_date BETWEEN '$daysago' AND '$today' AND post_status='publish' AND post_type='post' ORDER BY post_date DESC ");
27  foreach ($result as $Item) {
28  $post_ID[] = $Item->ID;
29  }
30  $num_current_post count($post_ID)+1;//当前文章发布以前的文章数量总数
31  $output .= $num_current_post.'/'<span class="crayon-sy">.$num_all_posts;
32  echo $output;
33}

显示上下篇及位置,在single.php

1<?php if (get_next_post()) { echo  next_post_link('%link'<span class="crayon-sy">,__( '<span title="上一篇:%title">上一篇</span>'<span class="crayon-sy">, 'lee'<span class="crayon-sy">),$in_same_cat = false,$excluded_categories '11'<span class="crayon-sy">);  } else echo '<a class="arc_nav_new">已最新</a>'<span class="crayon-sy">;  }?>
2<?php num_Pcurrent_post(); ?>
3  
4<?php num_Ncurrent_post(); ?>
5<?php if (get_previous_post()) { echo  previous_post_link('%link'<span class="crayon-sy">,__( '<span title="下一篇:%title">下一篇</span>'<span class="crayon-sy">, 'lee' <span class="crayon-sy">),$in_same_cat = false,$excluded_categories '11'<spanclass="crayon-sy">);  } else echo '<a class="arc_nav_new">已最后</a>'<span class="crayon-sy">;  }?>

12. 热门标签ajax加载

点击换一换

wordpress二次开发技巧之functions.php篇

01// 热门标签ajax部分
02function tagLoad(){
03    if( isset($_GET['action'<span class="crayon-sy">])){
04        if($_GET['action'<span class="crayon-sy">] == 'tag'<span class="crayon-h">  ){
05            echo wp_tag_cloud('smallest=10&largest=14&number=32&order=RAND'<span class="crayon-sy">);
06            die;
07        }
08    }
09  
10}
11add_action('init'<span class="crayon-sy">, 'tagLoad'<span class="crayon-sy">);

HTML部分

1<a class="tag_change" href="<?php echo get_option('home'<span class="crayon-sy">)."/?action=tag"; ?>">换一换</a>

使用JS实现点击交互

01// 标签云ajax
02    $(".tag_change").click(function(){
03        $.ajax({
04            url: $(this).attr("href"),
05            type: 'get'<span class="crayon-sy">,
06            beforeSend: function() {
07                // 可以显示loading
08            },
09            error: function(error) {
10                // 错误处理
11            },
12            success: function(data) {
13                // 成功返回数据,先清空初始标签,装载新数据淡入
14                $(".tag_content").empty().append($(data).fadeIn(200));
15            }
16        });
17        return false;
18    });

13. 外链加上nofollow

防止引入的网站有问题,被降权

01// 文章外部链接加上nofollow
02add_filter( 'the_content''cn_nf_url_parse');
03function cn_nf_url_parse( $content ) {
04  
05  $regexp "<as[^>]*href=("??)([^" >]*?)1[^>]*>";
06  if(preg_match_all("/$regexp/siU"$content$matches, PREG_SET_ORDER)) {
07    if( !empty($matches) ) {
08  
09      $srcUrl = get_option('siteurl');
10      for ($i=0; $i count($matches); $i++)
11      {
12  
13        $tag $matches[$i][0];
14        $tag2 $matches[$i][0];
15        $url $matches[$i][0];
16  
17        $noFollow '';
18  
19        $pattern '/targets*=s*"s*_blanks*"/';
20        preg_match($pattern$tag2$match, PREG_OFFSET_CAPTURE);
21        ifcount($match) < 1 )
22          $noFollow .= ' target="_blank" ';
23  
24        $pattern '/rels*=s*"s*[n|d]ofollows*"/';
25        preg_match($pattern$tag2$match, PREG_OFFSET_CAPTURE);
26        ifcount($match) < 1 )
27          $noFollow .= ' rel="nofollow" ';
28  
29        $pos strpos($url,$srcUrl);
30        if ($pos === false) {
31          $tag = rtrim ($tag,'>');
32          $tag .= $noFollow.'>';
33          $content str_replace($tag2,$tag,$content);
34        }
35      }
36    }
37  }
38  
39  $content str_replace(']]>'']]>'$content);
40  return $content;
41  
42}

14. 图片懒加载lazyload3. 外链加上nofollow

1function lazyload($content) {
2  if(!is_feed()||!is_robots) {
3    $content=preg_replace('/<img(.+)src=['"]([^'"]+)['"](.*)>/i',"<img$1data-original="$2" src="data:image/gif;base64,R0lGODlhAQABAIAAAOHh4QAAACH5BAAAAAAALAAAAAABAAEAQAICRAEAOw=="$3>n",$content);
4  }
5  return $content;
6}
7add_filter ('the_content''lazyload');

JS代码(需引入jquery.lazyload.js)

1// lazyload
2$("img").lazyload({
3    effect : "fadeIn",
4    threshold : 100,
5});

15. 获取文章中第一张图

如跑马灯图

wordpress二次开发技巧之functions.php篇

01// 获取文章中第一张图
02function wpdx_postimage($atts$content = null) {
03  extract(shortcode_atts(array(
04    "size" => 'full',
05    "float" => 'none'
06  ), $atts));
07  $images =& get_children( 'post_type=attachment&post_mime_type=image&post_parent='. get_the_id() );
08  foreach$images as $imageID => $imagePost )
09  $fullimage = wp_get_attachment_image($imageID$size, false);
10  $imagedata = wp_get_attachment_image_src($imageID$size, false);
11  $width = ($imagedata[1]+2);
12  $height = ($imagedata[2]+2);
13  return $fullimage;
14}
15add_shortcode("postimage""wpdx_postimage");

显示图片

1<a href="<?php the_permalink(); ?>" target="_blank">
2    <?php echo do_shortcode("[postimage]"); ?>
3</a>

16. 截取摘要

wordpress二次开发技巧之functions.php篇

01// 摘要字数限制
02function new_excerpt_length($length) {
03  return 100;
04}
05add_filter('excerpt_length''new_excerpt_length');
06  
07// 摘要...
08function new_excerpt_more( $more ) {
09  return '...';
10}
11add_filter('excerpt_more''new_excerpt_more');

17. 获取文章第一个分类目录

因为一篇文章可能属于多个目录,有些地方只需要输出一个

1// 获取文章第一个分类目录
2function get_first_category(){
3  $category = get_the_category();
4  if($category[0]){
5    echo '<a class="col_cat" href="'.get_category_link($category[0]->term_id ).'">'.$category[0]->cat_name.'</a>';
6  }
7}
8add_filter('get_first_category''get_first_category');

HTML

1<?php get_first_category(); ?>

18. 分类页获得文章简介

wordpress二次开发技巧之functions.php篇

1// 获得category简介
2function get_category_expert($length=240){
3  $content = get_the_content();
4  $trimmed_content = wp_trim_words( $content$length'<a href="'. get_permalink() .'"> [...]</a>' );
5  echo $trimmed_content;
6}
7add_filter('get_category_expert''get_category_expert');

19. 根据页面类型指定每页显示的文章数

01// 根据页面类型指定每页显示的文章数
02function custom_posts_per_page($query){
03    if(is_home()){
04        $query->set('posts_per_page',9);//首页每页显示8篇文章
05    }
06    if(is_search()){
07        $query->set('posts_per_page',5);//搜索页显示所有匹配的文章,不分页
08    }
09    if(is_archive()){
10        $query->set('posts_per_page',-1);//archive每页显示25篇文章
11      }
12    if(is_tag()){
13        $query->set('posts_per_page',4);//archive每页显示25篇文章
14    }
15    if(is_category()){
16        $query->set('posts_per_page',9);//archive每页显示25篇文章
17    }
18    if(is_category(11)){
19        $query->set('posts_per_page',-1);//archive每页显示25篇文章
20    }
21}//function
22//this adds the function above to the 'pre_get_posts' action
23add_action('pre_get_posts','custom_posts_per_page');

20. 缩略图

01//添加特色缩略图支持
02if ( function_exists('add_theme_support') )add_theme_support('post-thumbnails');
03  
04/*
05* 缩略图
06*/
07  
08function dm_the_thumbnail() {
09  
10    global $post;
11  
12    // 判断该文章是否设置的缩略图,如果有则直接显示
13  
14    if ( has_post_thumbnail() ) {
15  
16        echo '<a class="at_feature" href="'.get_permalink().'" title="阅读全文">';
17  
18        the_post_thumbnail('thumbnail');
19  
20        echo '</a>';
21  
22    else //如果文章没有设置缩略图,则查找文章内是否包含图片
23  
24        $content $post->post_content;
25  
26        preg_match_all('/<img.*?(?: |t|r|n)?src=['"]?(.+?)['"]?(?:(?: |t|r|n)+.*?)?>/sim', $content$strResult, PREG_PATTERN_ORDER);
27  
28        $n count($strResult[1]);
29  
30        if($n > 0){ // 如果文章内包含有图片,就用第一张图片做为缩略图
31            // 为了得到第一张图片的215x115尺寸,得用正则替换格式
32            $thumb_first $strResult[1][0];
33            $thumb_split strrpos($thumb_first'.');
34            $thumb_before substr($thumb_first, 0, $thumb_split);
35            $thumb_after substr($thumb_first$thumb_splitstrlen($thumb_first));
36            $reg "/-d*xd*/im";
37            $thumb_before = preg_replace($reg""$thumb_before);
38            $thumb_src $thumb_before.'-215x115'.$thumb_after;
39            echo '<a class="at_feature" href="'.get_permalink().'" title="阅读全文"><img class="animated" src="'.$thumb_src.'" alt="缩略图" /></a>';
40  
41        }else // 如果文章内没有图片,则用默认的图片。
42            $random= mt_rand(0, 19);
43            echo '<a class="at_feature" href="'.get_permalink().'" title="阅读全文"><img class="animated" src="'.get_bloginfo('template_url').'/images/thumbnail/default_thumbnail_'.$random.'.jpg" alt="缩略图" /></a>';
44  
45        }
46  
47    }
48  
49}

显示缩略图

1// 第一种
2<?php if (has_post_thumbnail()){ the_post_thumbnail();} ?>
3  
4 
5// 第二种
6<?php dm_the_thumbnail(); ?>

转载于:https://my.oschina.net/u/1266171/blog/1930599

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值