WordPress 主题获取版权信息

Copyright

WordPress 主题的版权信息一般在页脚显示,其内容经常需要手动修改,尤其是时间,这样比较麻烦,还容易忘记。使用下面的 PHP 代码可以动态的获取版权信息。

代码

代码一

/**
 * WordPress 主题动态获取版权信息
 * @author 智慧宫
 * @link   https://lerm.net
 */
function lerm_create_copyright() {
	$all_posts  = get_posts( 'post_status=publish&order=ASC' );
	$first_post = $all_posts[0];
	$first_date = $first_post->post_date_gmt;
	echo esc_html__( 'Copyright © ' );
	if ( substr( $first_date, 0, 4 ) === date( 'Y' ) ) {
		echo esc_html( date( 'Y' ) );
	} else {
		echo esc_html( substr( $first_date, 0, 4 ) . '-' . date( 'Y' ) );
	}
	echo ' <strong>' . esc_html( get_bloginfo( 'name' ) ) . '</strong> ';
	echo esc_html__( 'All rights reserved ' );
}

使用get_posts() 进行查询

代码二

/*
WordPress实现动态获取并显示版权年份
https://www.wpxzt.com
*/
function lerm_create_copyright() {
	global $wpdb;
	$copyright_dates = $wpdb->get_results(
		"
		SELECT
			YEAR(min(post_date_gmt)) AS firstdate,
			YEAR(max(post_date_gmt)) AS lastdate
		FROM
			$wpdb->posts
		WHERE post_status = 'publish'
	"
	);
	if ( $copyright_dates ) {
		$date      = date( 'Y-m-d' );
		$date      = explode( '-', $date );
		$copyright = 'Copyright &copy; ' . $copyright_dates[0]->firstdate;
		if ( $copyright_dates[0]->firstdate != $date[0] ) {
			$copyright .= '-' . $date[0];
		}
		echo esc_html( $copyright );
		echo ' <strong>' . esc_html( get_bloginfo( 'name' ) ) . '</strong> ';
		echo esc_html__( 'All rights reserved' );
	}
}

使用数据库进行查询

工作原理

以上两段代码的逻辑都是相同的,不同的是代码一使用了get_posts()函数进行查询,代码二使用$wpdb数据库进行查询获取时间。

  1. 获取所有已经发布的文章;
  2. 获取第一篇文章发布的年份并输出;
  3. 获取当前年份并输出;
  4. 获取博客名称并输出

使用方法

将上面的代码放在 functions.php 文件里面

在footer.php 文件里面相应的地方使用lerm_create_copyright()函数引用即可,在引用的地方可以看到如下的显示的版权信息了

Copyright © 2014-2020 智慧宫 All rights reserved

参考

https://www.zhutihome.net/7729.html

发表评论

游客欢迎您123