WP Bakery全局替换本地自定义字体 规避GDPR合规问题求助
解决WP Bakery批量替换Google Fonts为本地字体(GDPR合规)
方法一:通过PHP函数批量替换现有元素字体
直接在主题的functions.php中添加以下代码,过滤所有WP Bakery元素的输出,将指定的Google Fonts替换为你的本地字体:
// 注册本地字体(先确保字体文件已上传到主题目录的fonts文件夹) function enqueue_local_fonts() { wp_enqueue_style( 'local-custom-fonts', get_stylesheet_directory_uri() . '/fonts/custom-fonts.css' ); } add_action( 'wp_enqueue_scripts', 'enqueue_local_fonts' ); // 批量替换WP Bakery元素中的字体 function replace_wpbakery_fonts( $output ) { // 替换Google Fonts名称为你的本地字体名称,多个字体用|分隔 $google_fonts = 'Roboto|Open Sans|Lato'; $local_font = 'YourLocalFont, sans-serif'; $output = preg_replace( "/font-family:\s*['\"]?($google_fonts)['\"]?;/i", "font-family: $local_font;", $output ); return $output; } add_filter( 'vc_shortcode_output_filter', 'replace_wpbakery_fonts' );
注意:
- 先将本地字体文件(如
.woff2、.woff)上传到主题目录下的fonts文件夹,并创建custom-fonts.css定义字体:
@font-face { font-family: 'YourLocalFont'; src: url('your-local-font.woff2') format('woff2'), url('your-local-font.woff') format('woff'); font-weight: normal; font-style: normal; font-display: swap; }
- 根据实际使用的Google Fonts名称修改
$google_fonts变量,确保覆盖所有用到的字体。
方法二:重置所有WP Bakery元素为默认字体,再修改全局默认字体
步骤1:批量重置元素字体为默认
通过SQL语句直接更新数据库中WP Bakery的元素数据(操作前请备份数据库):
UPDATE wp_postmeta SET meta_value = REPLACE(meta_value, '"font_family":"Roboto"', '"font_family":""') WHERE meta_key LIKE '%vc_settings%' OR meta_key LIKE '%wpb_%';
替换Roboto为你要清除的字体名称,重复执行该语句替换所有用到的Google Fonts。
或者用PHP函数在functions.php中批量处理:
function reset_wpbakery_font_defaults() { global $wpdb; $google_fonts = array('Roboto', 'Open Sans', 'Lato'); foreach ($google_fonts as $font) { $wpdb->query( $wpdb->prepare( "UPDATE $wpdb->postmeta SET meta_value = REPLACE(meta_value, %s, %s) WHERE meta_key LIKE '%vc_settings%' OR meta_key LIKE '%wpb_%'", '"font_family":"' . $font . '"', '"font_family":""' ) ); } } // 执行一次后注释掉,避免重复执行 // reset_wpbakery_font_defaults();
步骤2:修改WP Bakery全局默认字体
在functions.php中添加代码,修改WP Bakery元素的默认字体设置:
function set_wpbakery_default_font( $settings ) { $settings['font_family'] = 'YourLocalFont, sans-serif'; return $settings; } add_filter( 'vc_element_get_default_settings', 'set_wpbakery_default_font' );
这样新添加的WP Bakery元素会默认使用本地字体,已重置的旧元素也会继承主题默认字体(需确保主题CSS中全局字体已设置为本地字体)。
内容的提问来源于stack exchange,提问作者Heni Ben Mimoun
相关产品推荐
相关产品推荐

