通过 child theme 修改 storefront 主题底部 credit 信息

更新日期: 2017-03-07 阅读次数: 12304 分类: wordpress

使用 storefront 主题之后,默认网页的底部会显示

Storefront designed by WooCommerce.

如果想去掉,最好采用 child theme 的方式。

不直接修改 storefront 的主题源代码的原因是,一旦主题升级,所有修改都会被覆盖掉。

首先,新建一个空的子主题

即在 /wp-content/themes 目录下新建一个目录,例如 zhongwei。然后在该目录下,新建两个文件

style.css 内容如下

/* 
Theme Name: zhongwei
Version: 1.0 
Description: Child theme for Storefront. 
Author: Zhongwei
Author URI: http://sunzhongwei.com 
Template: storefront 
*/ 

functions.php 置空即可。

这时,在后台将主题切换为 zhongwei 主题即可。这时,访问网站首页,你会发现网站没有任何变化。

通过 vim grep 可知,“Storefront designed by WooCommerce. ” 这段信息来自 storefront_credit 这个函数。所以,在子主题中将该函数覆盖即可。

将 /wp-content/themes/storefront/inc/storefront-template-functions.php 中的

if ( ! function_exists( 'storefront_credit' ) ) {
	/**
	 * Display the theme credit
	 *
	 * @since  1.0.0
	 * @return void
	 */
	function storefront_credit() {
		?>
		<div class="site-info">
			<?php echo esc_html( apply_filters( 'storefront_copyright_text', $content = '© ' . get_bloginfo( 'name' ) . ' ' . date( 'Y' ) ) ); ?>
			<?php if ( apply_filters( 'storefront_credit_link', true ) ) { ?>
			<br /> <?php printf( esc_attr__( '%1$s designed by %2$s.', 'storefront' ), 'Storefront', '<a href="http://www.woocommerce.com" title="WooCommerce - The Best eCommerce Platform for WordPress" rel="author">WooCommerce</a>' ); ?>
			<?php } ?>
		</div><!-- .site-info -->
		<?php
	}
}

复制到子主题的 functions.php 文件中,并做相应修改即可

if ( ! function_exists( 'storefront_credit' ) ) {
	/**
	 * Display the theme credit
	 *
	 * @since  1.0.0
	 * @return void
	 */
	function storefront_credit() {
		?>
		<div class="site-info">
			<?php echo esc_html( apply_filters( 'storefront_copyright_text', $content = '© ' . get_bloginfo( 'name' ) . ' ' . date( 'Y' ) ) ); ?>
			<?php if ( apply_filters( 'storefront_credit_link', true ) ) { ?>
			<br /> <?php printf( esc_attr__( '%1$s designed by %2$s.', 'storefront' ), '大象笔记', '<a href="http://www.sunzhongwei.com" title="zhongwei" rel="author">zhongwei</a>' ); ?>
			<?php } ?>
		</div><!-- .site-info -->
		<?php
	}
}

原理

If a function in the parent theme is pluggable, it allows you to copy a function from the parent theme into the child theme’s functions.php and have it replace the one in your parent theme. The only requirement is that the parent theme’s function is pluggable, which basically means it is wrapped in a conditional if statement e.g:

if (!function_exists("parent_function_name")) {
      parent_function_name() {
           ...
      } 
}

If the parent theme function is pluggable, you can copy it to the child theme functions.php and modify the function to your liking.

子主题的 functions.php 文件会先于父主题的 functions.php 被加载,只要父主题的某个函数是 pluggable 的,那么就可以在子主题中将其修改。

参考

关于作者 🌱

我是来自山东烟台的一名开发者,有敢兴趣的话题,或者软件开发需求,欢迎加微信 zhongwei 聊聊, 查看更多联系方式