Astra主题二次开发
在header.php引入bootstrap5的svg图标
通过CDN引入,但是有时候可能会加载缓慢
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css">
下载icon文件到本地引入,需要用到bootstrap-icons.min.css和fonts文件夹
添加博文页面的阅读次数统计功能
在functions.php中添加以下代码到post_meta数据库
// 获取文章的阅读次数
function get_post_views ($post_id) {
$count_key = 'views';
$count = get_post_meta($post_id, $count_key, true);
if ($count == '') {
delete_post_meta($post_id, $count_key);
add_post_meta($post_id, $count_key, '0');
$count = '0';
}
return number_format_i18n($count);
}
// 设置更新文章的阅读次数
function set_post_views () {
global $post;
$post_id = $post -> ID;
$count_key = 'views';
$count = get_post_meta($post_id, $count_key, true);
if (is_single() || is_page()) {
if ($count == '') {
delete_post_meta($post_id, $count_key);
add_post_meta($post_id, $count_key, '1');
} else {
update_post_meta($post_id, $count_key, $count + 1);
}
}
}
add_action('get_header', 'set_post_views');
在博文页面中显示,进入主题目录/inc/blog,打开博客配置文件blog-config.php,添加以下代码
if ( ! function_exists( 'astra_post_views' ) ) {
/**
* Function to get views applied of Post
*
* @param string $output_filter Output filter.
* @return html Markup.
*/
function astra_post_views( $output_filter = '' ) {
$output = '';
global $post;
/* translators: used between list items, there is a space after the comma */
$post_id = $post->ID;
$views = get_post_views($post_id);
$output .= '<span class="views bi bi-eye">' . $views . '</span>';
return apply_filters( 'astra_post_categories', $output, $output_filter );
}
}
在blog.php中的astra_blog_get_post_meta函数,向post_meta添加"views".
array_push($post_meta,'views');
在astra_get_post_meta函数中获取阅读次数,并展示到博客列表中。
case 'views':
$output_str .= ( 1 != $loop_count && '' != $output_str ) ? ' ' . $separator . ' ' : '';
$output_str .= astra_post_views();
break;
在 single-meta条件中添加’views’元素,实现在单个博客页面添加阅读次数展示
可以在astra_get_post_meta函数中自定义分隔符
国际站需要把站点语言设置成英文才会显示英文格式的meta信息