简介
WordPress是使用PHP语言开发的开源发布平台,用户可以在支持PHP和MySQL数据库的服务器上架设属于自己的博客、网站。也可以把WordPress当作一个内容管理系统(CMS)来使用。
官网
WordPress官网:中文官网。源码下载。
主题
WordPress官方主题:使用 11,896 个主题为您的 WordPress 站点增添样式。
:::: tabs
::: tab-pane 平台
WordPress大学:更新频次一般。
爱找主题:更新频次一般。
主题猫:很久更新了。
爱主题:一般吧。
模板兔:还可以。
:::
::: tab-pane 工作室
主题盒子:更新快停了,但是会员使用主题很便宜,适合入门。
WPCOM:有些主题效果不错,价格比较高。
知更鸟主题:SEO效果非常好。
:::
::: tab-pane 汉化
四亩地:比较不错的汉化工作室。
:::
::::
插件
WordPress官方插件:使用 59,751 个免费插件增强您的 WordPress 体验。
多域名多主题:不同域名显示不同主题来展示,常被运用在同一个WP内,中英文网站,手机网站的实现,下载。
功能
:::: collapse-panel accordion
::: collapse-item 历史上的今天
又是新的一年,网站也运行了好些年了,差不多可以给网站加上历史上的今天的功能了。
代码
//历史上的今天,代码来自柳城博主的WP-Today插件
function wp_today(){
global $wpdb;
$post_year = get_the_time('Y');
$post_month = get_the_time('m');
$post_day = get_the_time('j');
$sql = "select ID, year(post_date_gmt) as h_year, post_title, comment_count FROM
$wpdb->posts WHERE post_password = '' AND post_type = 'post' AND post_status = 'publish'
AND year(post_date_gmt)!='$post_year' AND month(post_date_gmt)='$post_month' AND day(post_date_gmt)='$post_day'
order by post_date_gmt DESC limit 5";
$histtory_post = $wpdb->get_results($sql);
if( $histtory_post ){
foreach( $histtory_post as $post ){
$h_year = $post->h_year;
$h_post_title = $post->post_title;
$h_permalink = get_permalink( $post->ID );
$h_comments = $post->comment_count;
$h_post .= "<li><strong>$h_year:</strong> <a href='".$h_permalink."' title='".$h_post_title."' target='_blank'>$h_post_title($h_comments)</a></li>";
}
}
if ( $h_post ){
$result = "<h2>历史上的今天:</h2><ul>".$h_post."</ul>";
}
return $result;
}
function wp_today_auto($content){
if( is_single() ){
$content = $content.wp_today();
}
return $content;
}
add_filter('the_content', 'wp_today_auto',9999);
将代码加入到当前主题的Functions.php文件中。
调用
<?php echo wp_today(); ?>
在需要调出历史今天的位置加上上面调出代码。对于CSS样式我们自行设置添加。
参考资料
wordpress插件发布:历史上的今天wp-today · 博客 · 柳城 · 2010年3月31日
:::
::: collapse-item 蜘蛛爬行记录统计
使用WordPress蜘蛛记录来生成这个功能。在对网站优化的研究中,清楚地了解蜘蛛的爬行规律也非常重要,这样才能了解蜘蛛的爬行规律。按照这个规则,我们会重新写文章,这符合蜘蛛的胃口,非常有利于优化
代码
将下方代码放入主题function.php文件。
function get_naps_bot(){
$useragent = strtolower($_SERVER['HTTP_USER_AGENT']);
if (strpos($useragent, 'googlebot') !== false){
return 'Googlebot';
}
if (strpos($useragent, 'msnbot') !== false){
return 'MSNbot';
}
if (strpos($useragent, 'slurp') !== false){
return 'Yahoobot';
}
if (strpos($useragent, 'baiduspider') !== false){
return 'Baiduspider';
}
if (strpos($useragent, 'sohu-search') !== false){
return 'Sohubot';
}
if (strpos($useragent, 'lycos') !== false){
return 'Lycos';
}
if (strpos($useragent, 'robozilla') !== false){
return 'Robozilla';
}
return false;
}
function nowtime(){
date_default_timezone_set('Asia/Shanghai');
$date=date("Y-m-d.G:i:s");
return $date;
}
$searchbot = get_naps_bot();
if ($searchbot) {
$tlc_thispage = addslashes($_SERVER['HTTP_USER_AGENT']);
$url=$_SERVER['HTTP_REFERER'];
$file="robotslogs.txt";
$time=nowtime();
$data=fopen($file,"a");
$PR="$_SERVER[REQUEST_URI]";
fwrite($data,"Time:$time robot:$searchbot URL:$tlc_thispage\n page:$PR\r\n");
fclose($data);
}
使用方法
然后在网站根目录创建一个 robotslogs.txt 并且给他777权限,查看统计的方式就是这样 https://域名/robotslogs.txt
:::
::: collapse-item 添加OG协议
OG协议也叫开放内容协议,是一套制定的Metatags规格,也就是Meta Property=og标签,用来标注页面信息,例如网站页面的标题、类型、页面地址、缩略图、视频/音频等地址信息。
好处
1、能够正确被蜘蛛抓取网站的内容到百度网页搜索。
2、帮助网站的内容更有效的在百度结构化展现。
3、能够正确的分享网站的内容到SNS网站。
4、帮助网站的内容更有效的在SNS网络中传播。
标签属性
<meta property="og:type" content="video"/>
<meta property="og:title" content="九秋笔记"/>
<meta property="og:image" content="http://yejiuqiu.cn/0100641F464A ... 9-76EA-E5E20A1887C4″/>
<meta property="og:url" content="http://v.youku.com/v_show/id_XMTIyMTY5NzMy.html"/>
<meta property="og:videosrc" content="http://player.youku.com/player.p ... AutoPlay=true/v.swf"/>
<meta property="og:width" content="500″ />
<meta property="og:height" content="416″ />
<meta property="og:type" content="video"/>
<meta property="og:title" content="叶九秋"/>
<meta property="og:image" content="http:/yejiuqiu.cn ... EA-E5E20A1887C44444″/>
<meta property="og:url" content="http://v.youku.com/v_show/id_XMTIyMTY5NzMyyyyyyyyyyyyyyyy.html"/>
<meta property="og:videosrc" content="http://yejiuqiu.cn"/>
<meta property="og:width" content="600″ />
<meta property="og:height" content="716″/>
标签属性
og:title 标题
og:type 类型 常用值:article book movie
og:image 略缩图地址
og:url 页面地址
og:description 页面的简单描述
og:site_name 页面所在网站名
og:videosrc 视频或者Flash地址
og:audiosrc 音频地址
WordPress
将以下代码复制到header.php的head之前,并分别绑上对应的数据,特别是数据啊,一定要绑,绑错wp或报错,或不出现,可以页面查看源代码查看是否绑定成功!
<meta property="og:type" content="acticle">
<meta property="og:title" content="<?php the_title();?>">
<meta property="og:site_name " content="<?php bloginfo('name'); ?>">
<meta property="og:description" content="<?php echo $description ?>">
<meta property="og:image" content="<?php echobloginfo('url').catch_that_image(); ?>">
<meta property="og:url" content="<?php the_permalink();?>"/>
:::
::: collapse-item 防止发布重复标题文章
对于我们WordPress建站或者是其它程序做网站,如果网站多个内容标题重复这并不见得是什么好事,从SEO上来讲更是让搜索引擎认为内容是重复的,并不知道给于哪个权重分配,所以今天咱们就给大家带来了WordPress防止发布重复标题文章。
请把以下代码丢到functions.php里面:
代码
// 发表文章页面,前端抓取标题并使用AJAX发送请求
add_action( 'admin_print_footer_scripts', 'duplicate_titles_enqueue_scripts', 100 );
function duplicate_titles_enqueue_scripts() {
?>
<script>
jQuery(function($){
function checkTitleAjax(title, id,post_type) {
var data = {
action: 'title_checks',
post_title: title,
post_type: post_type,
post_id: id
};
$.post(ajaxurl, data, function(response) {
$('#message').remove();
$('#poststuff').prepend('<div id=\"message\" class=\"updated below-h2 fade \"><p>'+response+'</p></div>');
});
};
$('#title').change(function() {
var title = $('#title').val();
var id = $('#post_ID').val();
var post_type = $('#post_type').val();
checkTitleAjax(title, id,post_type);
});
});
</script>
<?php
}
// 接收前端ajax参数
add_action('wp_ajax_title_checks', 'duplicate_title_checks_callback');
function duplicate_title_checks_callback(){
global $wpdb;
$title = $_POST['post_title'];
$post_id = $_POST['post_id'];
$titles = "SELECT post_title FROM $wpdb->posts WHERE post_status = 'publish' AND post_type = 'post'
AND post_title = '{$title}' AND ID != {$post_id} ";
$results = $wpdb->get_results($titles);
if($results) {
echo "<span style='color:red'>". _( '此标题已存在,请换一个标题!' , '' ) ." </span>";
} else {
echo '<span style="color:green">'._('恭喜,此标题未与其他文章标题重复!' , '').'</span>';
}
die();
}
// 检测后端标题并且避免同名文章更新草稿
add_action( 'publish_post','duplicate_titles_wallfa_bc' ) ;
function duplicate_titles_wallfa_bc( $post ){
global $wpdb ;
$title = $_POST['post_title'] ;
$post_id = $post ;
$wtitles = "SELECT post_title FROM $wpdb->posts WHERE post_status = 'publish' AND post_type = 'post'
AND post_title = '{$title}' AND ID != {$post_id} " ;
$wresults = $wpdb->get_results( $wtitles ) ;
if ( $wresults ){
$wpdb->update( $wpdb->posts, array( 'post_status' =>
'draft' ), array( 'ID' => $post ) ) ;
$arr_params = array( 'message' => '10', 'wallfaerror' => '1' ) ;
$location = add_query_arg( $arr_params , get_edit_post_link( $post , 'url' ) ) ;
wp_redirect( $location ) ;
exit ;
}
}
/// 文章提交更新后的提示
add_action( 'admin_notices', 'not_published_error_notice' );
function not_published_error_notice() {
if(isset($_GET['wallfaerror']) == 1 ){
?>
<div class="updated">
<p style='color:red' ><?php _e('貌似已经存在相同标题的文章,若您使用了文章别名作为固定链接,则可以通过修改本文的固定链接来使标题不再重复!' , '') ?></p>
</div>
<?php
}
}
// 禁用自动保存
add_action( 'wp_print_scripts', 'disable_autosave' ) ;
function disable_autosave(){
wp_deregister_script( 'autosave' ) ;
}
:::
::: collapse-item 搜索结果重定向
步骤
在 WordPress 进行搜索的时候,如果搜索结果只返回一篇日志的时候,最好的方法是直接跳转到文章页面。
我们可以在当前主题的 functions.php 文件添加下面的代码实现:
代码
add_action('template_redirect', 'wpjam_redirect_single_post');
function wpjam_redirect_single_post() {
if (is_search()) {
global $wp_query;
if ($wp_query->post_count == 1) {
wp_redirect( get_permalink( $wp_query->posts['0']->ID ) );
}
}
}
:::
::: collapse-item 站内搜索伪静态化
实现的方法很简单,只需要将以下代码加入到当前主题下的 functions.php 文件当中即可:
代码
//默认搜索伪静态
function wp_search_url_rewrite() {
if ( is_search() && ! empty( $_GET['s'] ) ) {
wp_redirect( home_url( "/search/" ) . urlencode( get_query_var( 's' ) ) . "/");
exit();
}
}
add_action( 'template_redirect', 'wp_search_url_rewrite' );
:::
::: collapse-item 自动缩略图
这是一篇为WordPress自动调用特色图像的代码,现在很多主题都自带了这功能,但是也有部分主题没有,那么就造成了一个问题之前网站的缩略图可以显示换了某个主题后就不显示了,需要设置特色图像,但是我文章很多一篇一篇的设置太麻烦了,所以就有了这篇教程。将以下代码添加到当前使用主题的functions.php文件中即可。
新增视频缩略图。
图片
function autoset_featured() {
global $post;
$already_has_thumb = has_post_thumbnail($post->ID);
if (!$already_has_thumb) {
$attached_image = get_children( "post_parent=$post->ID&post_type=attachment&post_mime_type=image&numberposts=1" );
if ($attached_image) {
foreach ($attached_image as $attachment_id => $attachment) {
set_post_thumbnail($post->ID, $attachment_id);
}
}
}
} //end function
add_action('the_post', 'autoset_featured');
add_action('save_post', 'autoset_featured');
add_action('draft_to_publish', 'autoset_featured');
add_action('new_to_publish', 'autoset_featured');
add_action('pending_to_publish', 'autoset_featured');
add_action('future_to_publish', 'autoset_featured');
视频
//提取视频封面
function catch_video_image() {
global $post, $posts;
$video_image = '';
ob_start();
ob_end_clean();
$output = preg_match_all('/<video.+poster=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
$video_image = $matches [1] [0];
return $video_image;
}
//正则提取字符串中视频url地址
function catch_that_video() {
global $post, $posts;
$first_video = '';
ob_start();
ob_end_clean();
$output = preg_match_all('/<video[^<>]*src=[\"]([^\"]+)[\"][^<>]*>/im', $post->post_content, $matches);
$first_video = $matches [1] [0];
return $first_video;
}
:::
::: collapse-item 简码实现任意页面自定义重定向
目前wordpress已经为我们提供了几种用户登陆后重定向的方法,所以在这篇文章中我将向大家介绍如何创建wordpress重定向的实用技巧,wordpress重定向这些方法可以让你设置用户登陆后重定向到你指定的页面,其中包括内部页面,外部页面或者当前页面。
代码
出于某种原因,您需要将WordPress站点的文章或页面临时重定向到另一个地址。那么WordPress任意页面重定向如何设置呢?有现成的插件可供使用,但强迫症不喜欢;当然,您也可以将js代码实现添加到需要转换的页面中,这不够方便或优雅。
因此,使用简单代码(shortcode)来实现它。添加一个新的简单代码,以便使用一段简短的代码引导到站点,因此每次向需要翻转的页面或文章添加简单代码时,您都可以很容易地使用它。将以下代码添加到主题functions.php中:
// 1. 重定向简码实现
function my_redirect_shortcode($params) {
// 提取参数
extract(shortcode_atts(array(
'url' => '/',
), $params));
// 功能实现
header('Location: '.$url);
}
// 2. 简码注册函数
function my_add_shortcodes() {
add_shortcode( 'my-redirect', 'my_redirect_shortcode' );
}
// 3. 在初始化时注册简码
add_action( 'init', 'my_add_shortcodes' );
在需要跳转的页面或文章中,用一小段代码给站点增加一个新的用于转向的简码,只要在文章内容里加入这么一句话,即可轻松转向:
[my_redirect url="http://yejiuqiu.cn"]
:::
::: collapse-item 自动获取网站截图
我们分享一些好的网站或者网页模板时,配上对应的网页截图会更加直观。或者在做网站目录或博客目录的时候,同样可以通过本文的方法获取所收录的目标网站首页截图,这样可以节省很多时间和精力。下面我们分享 wordpress 文章中自动获取网站截图的纯代码方法:
短代码
将下面的代码添加到当前主题函数模板 functions.php 中:
function wp_screenshot($atts, $content=null){
extract(
shortcode_atts(
array(
"shots" => "https://s0.wordpress.com/mshots/v1/",
"url" => "https://www.wpbeginner.com",
"width" => "600",
"height" => "450",
"alt" => "screenshot"
),
$atts
)
);
$img = '<div class="wp-shot"><a href="' . $url . '" rel="external nofollow noopener noreferrer" target="_blank"><img src="' . $shots . '' . urlencode($url) . '?w=' . $width . '&h=' . $height . '" alt="' . $alt . '" /></a></div>';
return $img;
}
add_shortcode("shot", "wp_screenshot");
发表文章时,添加短代码:
[shot url="http://yejiuqiu.cn/"]
或者自定义截图大小
[shot url="http://yejiuqiu.cn/" width="600" height="450"]
修改其中的网址链接链接即可。
直接添加链接
这个方法使用更加方便,获取截图的基本格式:
https://s0.wordpress.com/mshots/v1/http://yejiuqiu.cn/?w=600&h=450
也可以直接将上述地址链接格式像正常插入图片一样添加到文章中,上面的就是这么加的,并没有用短代码。
温馨提示:因需要即时生成截图,第一次打开可能看不到图片,刷新一下就可以了,不行就多刷新几次。生成的截图存储在 WordPress.com 服务器上,不会占用自己的空间,不过加载可能有些慢。
演示
:::
::: collapse-item 文章只允许搜索引擎查看
有些文章只是为了SEO才发布的,想让这些文章只允许搜索引擎抓取,普通的访客无法查看,在WordPress中如何做到?
代码
// 给文章和页面的编辑页添加选项
function ludouseo_add_custom_box() {
add_meta_box('ludou_se_only', '搜索引擎专属', 'ludou_se_only', 'post', 'side', 'low');
add_meta_box('ludou_se_only', '搜索引擎专属', 'ludou_se_only', 'page', 'side', 'low');
}
add_action('add_meta_boxes', 'ludouseo_add_custom_box');
function ludou_se_only() {
global $post;
//添加验证字段
wp_nonce_field('ludou_se_only', 'ludou_se_only_nonce');
$meta_value = get_post_meta($post->ID, 'ludou_se_only', true);
if($meta_value)
echo '<input name="ludou-se-only" type="checkbox" checked="checked" value="1" /> 只允许搜索引擎查看';
else
echo '<input name="ludou-se-only" type="checkbox" value="1" /> 只允许搜索引擎查看';
}
// 保存选项设置
function ludouseo_save_postdata($post_id) {
// 验证
if ( !isset( $_POST['ludou_se_only_nonce']))
return $post_id;
$nonce = $_POST['ludou_se_only_nonce'];
// 验证字段是否合法
if (!wp_verify_nonce( $nonce, 'ludou_se_only'))
return $post_id;
// 判断是否自动保存
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE)
return $post_id;
// 验证用户权限
if ('page' == $_POST['post_type']) {
if ( !current_user_can('edit_page', $post_id))
return $post_id;
}
else {
if (!current_user_can('edit_post', $post_id))
return $post_id;
}
// 更新设置
if(!empty($_POST['ludou-se-only']))
update_post_meta($post_id, 'ludou_se_only', '1');
else
delete_post_meta($post_id, 'ludou_se_only');
}
add_action('save_post', 'ludouseo_save_postdata');
function do_ludou_se_only() {
// 本功能只对文章和页面有效
if(is_singular()) {
global $post;
$is_robots = 0;
$ludou_se_only = get_post_meta($post->ID, 'ludou_se_only', true);
if(!empty($ludou_se_only)) {
// 下面是搜索引擎Agent判断关键字数组
// 有点简单,自己优化一下吧
$bots = array(
'spider',
'bot',
'crawl',
'Slurp',
'yahoo-blogs',
'Yandex',
'Yeti',
'blogsearch',
'ia_archive',
'Google'
);
$useragent = $_SERVER['HTTP_USER_AGENT'];
if(!empty($useragent)) {
foreach ($bots as $lookfor) {
if (stristr($useragent, $lookfor) !== false) {
$is_robots = 1;
break;
}
}
}
// 如果不是搜索引擎,就显示错误信息
// 已登录的用户不受影响
if(!$is_robots && !is_user_logged_in()) {
wp_die('您无权查看此文!');
}
}
}
}
add_action('wp', 'do_ludou_se_only');
使用方法
成功添加以上代码到当前主题的functions.php后,我们就可以正常使用了,完全傻瓜式。在WordPress后台文章和页面的编辑页面,右边栏底部我们可以看到一个选框。
如果当前文章/页面需要禁止搜索引擎抓取,勾选即可。勾选后,当此文章/页面被普通访客访问时就会显示“您无权查看此文!”(搜索引擎和已登录用户不受影响)。
:::
::: collapse-item 上传文件重命名
WordPress上传文件默认是不改变文件名称的,可对中文文件名而言,某些系统、某些浏览器访问是会出现问题,文件重命名可以有效的规范文件管理,不会造成文件重复,覆盖,错误等问题。
按照时间重命名
//wordpress上传文件重命名
function git_upload_filter($file) {
$time = date("YmdHis");
$file['name'] = $time . "" . mt_rand(1, 100) . "." . pathinfo($file['name'], PATHINFO_EXTENSION);
return $file;
}
add_filter('wp_handle_upload_prefilter', 'git_upload_filter');
MD5加密重命名
function rename_filename($filename) {
$info = pathinfo($filename);
$ext = emptyempty($info['extension']) ? '' : '.' . $info['extension'];
$name = basename($filename, $ext);
return substr(md5($name), 0, 8) . $ext;
}
add_filter('sanitize_file_name', 'rename_filename', 10);
使用
把这段代码加入到主题的functions.php中,你就会发现神奇的事情发生了,文件已上传就重命名了。
:::
::: collapse-item 随便看看
随机在博客中抽取一篇文章来访问。
将以下代码加入到主题目录中的“functions.php”文件的 ?> 之前即可。
代码
// 添加随便看看
function random_postlite() {
global $wpdb;
$query = "SELECT ID FROM $wpdb->posts WHERE post_type = 'post' AND post_password = '' AND post_status = 'publish' ORDER BY RAND() LIMIT 1";
if ( isset( $_GET['random_cat_id'] ) ) {
$random_cat_id = (int) $_GET['random_cat_id'];
$query = "SELECT DISTINCT ID FROM $wpdb->posts AS p INNER JOIN $wpdb->term_relationships AS tr ON (p.ID = tr.object_id AND tr.term_taxonomy_id = $random_cat_id) INNER JOIN $wpdb->term_taxonomy AS tt ON(tr.term_taxonomy_id = tt.term_taxonomy_id AND taxonomy = 'category') WHERE post_type = 'post' AND post_password = '' AND post_status = 'publish' ORDER BY RAND() LIMIT 1";
}
if ( isset( $_GET['random_post_type'] ) ) {
$post_type = preg_replace( '|[^a-z]|i', '', $_GET['random_post_type'] );
$query = "SELECT ID FROM $wpdb->posts WHERE post_type = '$post_type' AND post_password = '' AND post_status = 'publish' ORDER BY RAND() LIMIT 1";
}
$random_id = $wpdb->get_var( $query );
wp_redirect( get_permalink( $random_id ) );
exit;
}
if ( isset( $_GET['random'] ) )
add_action( 'template_redirect', 'random_postlite' );
// 随便看看结束
使用方法
1、访问你网站的域名/?random即可看到效果,如: yejiuqiu.cn/?random
2、如果要在导航菜单现实的话,在后台新建一个自定义URL菜单即可。
3、也可以自己建一个PHP文件把代码复件进去调用也是可以的。
:::
::: collapse-item 文章关键词自动添加链接
文章页面的关键词自动添加 超级链接,也就是所谓的内链,主要的是有利于 SEO,有利于读者方便查看所有相关关键词的所有文章,也就是对关键词进行了站内搜索。在主题的 functions.php 文件中添加以下代码:
代码
/*
*自动为文章内的标签添加内链开始
*/
//连接数量
$match_num_from = 1; //一个关键字少于多少不替换
$match_num_to = 1; //一个关键字最多替换次数
//连接到wordpress的模块
add_filter('the_content','tag_link',1);
//按长度排序
function tag_sort($a, $b){
if ( $a->name == $b->name ) return 0;
return ( strlen($a->name) > strlen($b->name) ) ? -1 : 1;
}
//改变标签关键字
function tag_link($content){
global $match_num_from,$match_num_to;
$posttags = get_the_tags();
if ($posttags) {
usort($posttags, "tag_sort");
foreach($posttags as $tag) {
$link = get_tag_link($tag->term_id);
$keyword = $tag->name;
//连接代码
$cleankeyword = stripslashes($keyword);
$url = "<a href=\"$link\" title=\"".str_replace('%s',addcslashes($cleankeyword, '$'),__('查看所有文章关于 %s'))."\"";
$url .= 'target="_blank"';
$url .= ">".addcslashes($cleankeyword, '$')."</a>";
$limit = rand($match_num_from,$match_num_to);
//不连接的代码
$content = preg_replace( '|(<a[^>]+>)(.*)('.$ex_word.')(.*)(</a[^>]*>)|U'.$case, '$1$2%&&&&&%$4$5', $content);
$content = preg_replace( '|(<img)(.*?)('.$ex_word.')(.*?)(>)|U'.$case, '$1$2%&&&&&%$4$5', $content);
$cleankeyword = preg_quote($cleankeyword,'\'');
$regEx = '\'(?!((<.*?)|(<a.*?)))('. $cleankeyword . ')(?!(([^<>]*?)>)|([^>]*?</a>))\'s' . $case;
$content = preg_replace($regEx,$url,$content,$limit);
$content = str_replace( '%&&&&&%', stripslashes($ex_word), $content);
}
}
return $content;
}
:::
::: collapse-item 登陆背景设置
为wordpress设置好看点的登陆背景。
必应壁纸
将以下代码加入至主题目录 Functions.php 文件最后面?>标签前(如果没有?>标签,则直接加到最后面)保存:
/**自定义登录界面背景*/
//调用bing美图作为登录页背景图
function custom_login_head(){
$str=file_get_contents('http://cn.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1');
if (preg_match("/\/(.+?).jpg/", $str, $matches)) {
$imgurl='http://s.cn.bing.net'.$matches[0];
}
echo'<style type="text/css">body{background: url('.$imgurl.');background-image:url('.$imgurl.');-moz-border-image: url('.$imgurl.');}</style>';
//这里我对background图片的样式进行了调整
//方便小分辨率屏幕(如手机)显示图片正常,否则会被压缩
}
add_action('login_head', 'custom_login_head');
:::
::: collapse-item 文章有更新提示
可能我们前两年写得文章内容已经跟现在的情况不太符合了,特别是一些教程攻略,可能随着软件、数据的更新不再准确。相信建站时间长的朋友可能需要用到,因为由于建站时间较长,部分文件内容已经失效了,为了让博客网友体验更好,我们可以通过此方法为那些长期没有更新的文章添加一段文字提示。
代码
//添加老文章提示信息
function old_content_message($content) {
$modified = get_the_modified_time('U');
$current = current_time('timestamp');
$diffTime = ($current - $modified) / (60 * 60 * 24);
if ($diffTime > 365) {
$content = $content.'<div class="warn">本文最后更新于'.get_the_modified_time('Y年n月j日').
',已超过 1 年没有更新,涉及的内容可能已经失效!</div>';
}
return $content;
}
add_filter('the_content', 'old_content_message');
如果你想该提示框出现在文章的开头,则需要将代码改下:将$content 放在提示后面。
//添加老文章提示信息
function old_content_message($content) {
$modified = get_the_modified_time('U');
$current = current_time('timestamp');
$diffTime = ($current - $modified) / (60 * 60 * 24);
if ($diffTime > 365) {
$content = '<div class="warn">本文最后更新于'.get_the_modified_time('Y年n月j日').
',已超过 1 年没有更新,如果文章内容或图片资源失效,请留言反馈,我们会及时处理,谢谢!</div>'.$content;
}
return $content;
}
add_filter('the_content', 'old_content_message');
CSS样式
/* 提醒 */
.warn {
color: #ad9948;
background: #fff4b9 url(img/warn.png) -1px -1px no-repeat;
border: 1px solid #eac946;
overflow: hidden;
margin: 10px 0;
padding: 15px 15px 15px 35px;
font-size: 14px;
}
延伸
本功能使用了WordPress的get_the_modified_time函数,它可以获得文章的最后修改时间,包括你对内容、标签、置顶等信息的修改都会影响最后修改时间。第五行606024是将计时单位(秒)转化成(天),第六行>365即最后修改时间大于一年的文章将会出现提示,你可以根据具体情况进行修改。
另外我们还可以控制哪些文章显示提醒,例如你只想让ID为8的分类中的文章显示提示信息,只需要将第六行代码添加判断条件即可,如下:
if($diffTime > 365 && in_category(8) ){
多个分类的话用数组形式添加,如让ID为8、9、10的分类文章显示提示信息,则修改第六行为
if($diffTime > 365 && in_category(array(8,9,10)) ){
同理如果想排除某些分类,除了这些分类的文章都显示提示信息,只需要在in_category前添加半角“!”既可,如不想让ID为8、9、10的分类文章显示提示信息,则修改第六行为
if($diffTime > 365 && !in_category(array(8,9,10)) ){
:::
::::
求知
网站
WordPress 操作指南:入门教程。