10. 自定义登录界面


// 自定义登录界面
function custom_login(){
    echo '<link rel="stylesheet" type="text/css" href="' . get_bloginfo('template_directory') . '/css/login.css" />';
}
add_action('login_head', 'custom_login');

function login_headerurl($url) {
    return get_bloginfo('url');
}
add_filter('login_headerurl', 'login_headerurl');

function login_headertitle($title){
    return __('RK');
}
add_filter('login_headertitle', 'login_headertitle');

11. 获得当前文章的位置


// 当前文章
function num_Pcurrent_post() {
  global $wpdb;
  $postid = get_the_ID();//获取当前文章的ID
  $getpost = get_post($postid);
  $daysago = $getpost->post_date;//获取当前文章的发布时间
  $today = gmdate('Y-m-d H:i:s', time() + 3600 * 8);//获取当前服务器的时间
  $count_posts = wp_count_posts();
  $num_all_posts = $count_posts->publish;//总的文章数量
  $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 ");
  foreach ($result as $Item) {
  $post_ID[] = $Item->ID;
  }
  $num_current_post = count($post_ID)-1;//当前文章发布以前的文章数量总数
  $output .= $num_current_post.'/'.$num_all_posts;
  echo $output;
}
function num_Ncurrent_post() {
  global $wpdb;
  $postid = get_the_ID();//获取当前文章的ID
  $getpost = get_post($postid);
  $daysago = $getpost->post_date;//获取当前文章的发布时间
  $today = gmdate('Y-m-d H:i:s', time() + 3600 * 8);//获取当前服务器的时间
  $count_posts = wp_count_posts();
  $num_all_posts = $count_posts->publish;//总的文章数量
  $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 ");
  foreach ($result as $Item) {
  $post_ID[] = $Item->ID;
  }
  $num_current_post = count($post_ID)+1;//当前文章发布以前的文章数量总数
  $output .= $num_current_post.'/'.$num_all_posts;
  echo $output;
}

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


<?php if (get_next_post()) { echo  next_post_link('%link',__( '<span title="上一篇:%title">上一篇</span>', 'lee' ),$in_same_cat = false,$excluded_categories = '11');  } else { echo '<a class="arc_nav_new">已最新</a>';  }?>
<?php num_Pcurrent_post(); ?>

<?php num_Ncurrent_post(); ?>
<?php if (get_previous_post()) { echo  previous_post_link('%link',__( '<span title="下一篇:%title">下一篇</span>', 'lee' ),$in_same_cat = false,$excluded_categories = '11');  } else { echo '<a class="arc_nav_new">已最后</a>';  }?>

12. 热门标签ajax加载


// 热门标签ajax部分
function tagLoad(){
    if( isset($_GET['action'])){
        if($_GET['action'] == 'tag'  ){
            echo wp_tag_cloud('smallest=10&largest=14&number=32&order=RAND');
            die;
        }
    }

}
add_action('init', 'tagLoad');
//HTML部分
<a class="tag_change" href="<?php echo get_option('home')."/?action=tag"; ?>">换一换</a>

使用JS实现点击交互


// 标签云ajax
    $(".tag_change").click(function(){
    	$.ajax({
            url: $(this).attr("href"),
            type: 'get',
            beforeSend: function() {
            	// 可以显示loading
            },
            error: function(error) {
				// 错误处理
            },
            success: function(data) {
            	// 成功返回数据,先清空初始标签,装载新数据淡入
                $(".tag_content").empty().append($(data).fadeIn(200));
            }
        });
        return false;
    });

13. 外链加上nofollow

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


// 文章外部链接加上nofollow
add_filter( 'the_content', 'cn_nf_url_parse');
function cn_nf_url_parse( $content ) {

  $regexp = "<a\s[^>]*href=(\"??)([^\" >]*?)\\1[^>]*>";
  if(preg_match_all("/$regexp/siU", $content, $matches, PREG_SET_ORDER)) {
    if( !empty($matches) ) {

      $srcUrl = get_option('siteurl');
      for ($i=0; $i < count($matches); $i++)
      {

        $tag = $matches[$i][0];
        $tag2 = $matches[$i][0];
        $url = $matches[$i][0];

        $noFollow = '';

        $pattern = '/target\s*=\s*"\s*_blank\s*"/';
        preg_match($pattern, $tag2, $match, PREG_OFFSET_CAPTURE);
        if( count($match) < 1 )
          $noFollow .= ' target="_blank" ';

        $pattern = '/rel\s*=\s*"\s*[n|d]ofollow\s*"/';
        preg_match($pattern, $tag2, $match, PREG_OFFSET_CAPTURE);
        if( count($match) < 1 )
          $noFollow .= ' rel="nofollow" ';

        $pos = strpos($url,$srcUrl);
        if ($pos === false) {
          $tag = rtrim ($tag,'>');
          $tag .= $noFollow.'>';
          $content = str_replace($tag2,$tag,$content);
        }
      }
    }
  }

  $content = str_replace(']]>', ']]>', $content);
  return $content;

}

14. 图片懒加载lazyload


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

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


// lazyload
$("img").lazyload({
	effect : "fadeIn",
	threshold : 100,
});

15. 获取文章中第一张图


// 获取文章中第一张图
function wpdx_postimage($atts, $content = null) {
  extract(shortcode_atts(array(
    "size" => 'full',
    "float" => 'none'
  ), $atts));
  $images =& get_children( 'post_type=attachment&post_mime_type=image&post_parent=' . get_the_id() );
  foreach( $images as $imageID => $imagePost )
  $fullimage = wp_get_attachment_image($imageID, $size, false);
  $imagedata = wp_get_attachment_image_src($imageID, $size, false);
  $width = ($imagedata[1]+2);
  $height = ($imagedata[2]+2);
  return $fullimage;
}
add_shortcode("postimage", "wpdx_postimage");
//显示图片
<a href="<?php the_permalink(); ?>" target="_blank">
	<?php echo do_shortcode("[postimage]"); ?>
</a>

16. 截取摘要


// 摘要字数限制
function new_excerpt_length($length) {
  return 100;
}
add_filter('excerpt_length', 'new_excerpt_length');

// 摘要...
function new_excerpt_more( $more ) {
  return '...';
}
add_filter('excerpt_more', 'new_excerpt_more');

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

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


// 获取文章第一个分类目录
function get_first_category(){
  $category = get_the_category();
  if($category[0]){
    echo '<a class="col_cat" href="'.get_category_link($category[0]->term_id ).'">'.$category[0]->cat_name.'</a>';
  }
}
add_filter('get_first_category', 'get_first_category');
//HTML
<?php get_first_category(); ?>

18. 分类页获得文章简介


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

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


// 根据页面类型指定每页显示的文章数
function custom_posts_per_page($query){
    if(is_home()){
        $query->set('posts_per_page',9);//首页每页显示8篇文章
    }
    if(is_search()){
        $query->set('posts_per_page',5);//搜索页显示所有匹配的文章,不分页
    }
    if(is_archive()){
        $query->set('posts_per_page',-1);//archive每页显示25篇文章
      }
    if(is_tag()){
        $query->set('posts_per_page',4);//archive每页显示25篇文章
    }
    if(is_category()){
        $query->set('posts_per_page',9);//archive每页显示25篇文章
    }
    if(is_category(11)){
        $query->set('posts_per_page',-1);//archive每页显示25篇文章
    }
}//function
//this adds the function above to the 'pre_get_posts' action
add_action('pre_get_posts','custom_posts_per_page');

20. 缩略图


//添加特色缩略图支持
if ( function_exists('add_theme_support') )add_theme_support('post-thumbnails');

/*
* 缩略图
*/

function dm_the_thumbnail() {

    global $post;

    // 判断该文章是否设置的缩略图,如果有则直接显示

    if ( has_post_thumbnail() ) {

        echo '<a class="at_feature" href="'.get_permalink().'" title="阅读全文">';

        the_post_thumbnail('thumbnail');

        echo '</a>';

    } else { //如果文章没有设置缩略图,则查找文章内是否包含图片

        $content = $post->post_content;

        preg_match_all('/<img.*?(?: |\\t|\\r|\\n)?src=[\'"]?(.+?)[\'"]?(?:(?: |\\t|\\r|\\n)+.*?)?>/sim', $content, $strResult, PREG_PATTERN_ORDER);

        $n = count($strResult[1]);

        if($n > 0){ // 如果文章内包含有图片,就用第一张图片做为缩略图
            // 为了得到第一张图片的215x115尺寸,得用正则替换格式
            $thumb_first = $strResult[1][0];
            $thumb_split = strrpos($thumb_first, '.');
            $thumb_before = substr($thumb_first, 0, $thumb_split);
            $thumb_after = substr($thumb_first, $thumb_split, strlen($thumb_first));
            $reg = "/-\d*x\d*/im";
            $thumb_before = preg_replace($reg, "", $thumb_before);
            $thumb_src = $thumb_before.'-215x115'.$thumb_after;
            echo '<a class="at_feature" href="'.get_permalink().'" title="阅读全文"><img decoding="async" class="animated" src="'.$thumb_src.'" alt="缩略图" /></a>';

        }else { // 如果文章内没有图片,则用默认的图片。
            $random= mt_rand(0, 19);
            echo '<a class="at_feature" href="'.get_permalink().'" title="阅读全文"><img decoding="async" class="animated" src="'.get_bloginfo('template_url').'/images/thumbnail/default_thumbnail_'.$random.'.jpg" alt="缩略图" /></a>';

        }

    }

}

显示缩略图


// 第一种
<?php if (has_post_thumbnail()){ the_post_thumbnail();} ?>
// 第二种
<?php dm_the_thumbnail(); ?>