一般不建议在子主题中直接修改header.php、footer.php等文件,而是在使用WP或主题的钩子实现功能,以下功能均在子主题的functions.php中定义。
1.在header中插入script脚本
add_action('astra_head_top', 'add_google_gtag_header');
function add_google_gtag_header() {
?>
<!-- Google tag (gtag.js) -->
<script
async
src="https://www.googletagmanager.com/gtag/js?id=AW-188888888888"
></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag() {
dataLayer.push(arguments);
}
gtag('js', new Date());
gtag('config', 'AW-188888888888');
</script>
<?php
}
保存文件之后即可在站点打开浏览器控制台检查脚本有没有加载成功。
2.添加悬浮按钮
add_action('astra_footer_after', 'add_floating_contact_buttons');
function add_floating_contact_buttons() {
?>
<div class="contact">
<a href="https://telegram.org/" rel="nofollow" target="_blank" class="floating-button telegram-button" ></a>
<a href="https://im.qq.com/index/" rel="nofollow" target="_blank" class="floating-button qq-button" ></a>
</div>
<?php
}
在style.css中添加样式:
/* ========== 页脚悬浮按钮 ======== */
/* 基础样式 */
.floating-button {
position: fixed;
right: 24px;
bottom: 100px;
width: 60px;
height: 60px;
background: #1dc9ca;
color: white;
border-radius: 50%;
text-align: center;
line-height: 60px;
font-size: 24px;
cursor: pointer;
z-index: 999;
transition: all 0.3s;
}
.telegram-button {
background: url('https://pics1.baidu.com/feed/a6efce1b9d16fdfa7464c33324ea785a95ee7b53.png@f_auto?token=7d3c5186e2249cd83f318f8a2c5ec26a')
no-repeat;
background-size: 100% 100%;
}
.qq-button {
bottom: 180px;
background: url('https://img0.baidu.com/it/u=3177308708,1024606623&fm=253&app=138&f=JPEG?w=800&h=800')
no-repeat;
background-size: 100% 100%;
}
/* 悬停效果 */
.floating-button:hover {
transform: scale(1.1);
}
/* 移动端适配 */
@media (max-width: 768px) {
.floating-button {
display: none;
}
}
@media (max-height: 600px) {
.floating-button {
right: 14px;
bottom: 90px;
width: 54px;
height: 54px;
}
.qq-button {
bottom: 170px;
}
}
/* ========== 悬浮元素(end)======== */
保存文件之后,即可在站点页面右下角看到自定义的悬浮按钮了。
3.给页面添加分类功能
类似文章的分类,默认页面是没有这个功能的,自己定义一个。
法1:会与文章共享分类,做分类查询时,会把文章和页面同时查询出来
// 为页面添加分类功能
function add_categories_to_pages() {
register_taxonomy_for_object_type('category', 'page');
}
add_action('init', 'add_categories_to_pages');
// 为页面添加标签功能
function add_tags_to_pages() {
register_taxonomy_for_object_type('post_tag', 'page');
}
add_action('init', 'add_tags_to_pages');
// 确保分类和标签在后台页面编辑中显示
function page_category_support() {
register_taxonomy_for_object_type('category', 'page');
register_taxonomy_for_object_type('post_tag', 'page');
}
add_action('admin_init', 'page_category_support');
法2:使用独立的分类系统,不与文章混合使用
function create_page_only_categories() {
$args = array(
'hierarchical' => true,
'labels' => array(
'name' => '页面分类',
'singular_name' => '页面分类'
),
'show_ui' => true,
'show_admin_column' => true,
'query_var' => true,
'rewrite' => array('slug' => 'page-category'),
'show_in_rest' => true
);
register_taxonomy('page_category', array('page'), $args);
}
add_action('init', 'create_page_only_categories');
保存代码后刷新后台,即可看到页面菜单下出现页面分类的子菜单了。