如何在TwentyTwenty子主题中重写/inc/template-tags.php?需修改functions.php
直接复制父主题代码到子主题functions.php报错,核心原因是父主题的函数已经被定义,重复定义会触发PHP致命错误,下面是正确的处理步骤:
1. 定位要修改的目标函数
打开父主题的/inc/template-tags.php,找到你需要修改的具体函数(比如twentytwenty_posted_on()、twentytwenty_posted_by()这类),先看函数的定义结构:
情况1:父主题函数用function_exists包裹
如果父主题的函数是这样定义的:
if ( ! function_exists( 'twentytwenty_posted_on' ) ) : function twentytwenty_posted_on() { // 父主题原代码逻辑 } endif;
这种情况下,直接在子主题的functions.php里重新定义同名函数即可覆盖,子主题的函数会优先被加载。示例:
function twentytwenty_posted_on() { // 这里写你的自定义逻辑,比如修改日期显示格式 $time_string = '<time class="entry-date published updated" datetime="%1$s">%2$s</time>'; if ( get_the_time( 'U' ) !== get_the_modified_time( 'U' ) ) { $time_string = '<time class="entry-date published" datetime="%1$s">%2$s</time><time class="updated" datetime="%3$s">%4$s</time>'; } $time_string = sprintf( $time_string, esc_attr( get_the_date( DATE_W3C ) ), esc_html( get_the_date( 'Y年m月d日' ) ), // 自定义日期格式 esc_attr( get_the_modified_date( DATE_W3C ) ), esc_html( get_the_modified_date( 'Y年m月d日' ) ) ); $posted_on = sprintf( esc_html_x( '发布于 %s', 'post date', 'twentytwenty' ), '<a href="' . esc_url( get_permalink() ) . '" rel="bookmark">' . $time_string . '</a>' ); echo '<span class="posted-on">' . $posted_on . '</span>'; }
情况2:父主题函数未用function_exists包裹
如果父主题的函数直接定义(没有包裹判断),就需要先移除它的钩子绑定,再添加自己的自定义函数。示例:
// 先移除父主题函数的钩子 remove_action( 'twentytwenty_entry_meta', 'twentytwenty_posted_on' ); // 绑定自己的自定义函数到同一个钩子 add_action( 'twentytwenty_entry_meta', 'my_custom_posted_on' ); // 定义自定义函数 function my_custom_posted_on() { // 你的自定义逻辑代码 echo '<span class="posted-on">自定义发布时间:' . esc_html( get_the_date() ) . '</span>'; }
关键注意事项
- 不要复制整个父主题的
template-tags.php到子主题,也不要盲目复制部分代码,只针对需要修改的单个函数处理。 - 修改前务必备份子主题的
functions.php,避免出错后无法恢复。 - 确保自定义函数的参数、钩子绑定逻辑和原函数一致,避免破坏主题的原有布局。
内容的提问来源于stack exchange,提问作者danodev
相关产品推荐
相关产品推荐

