微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何更改 Wordpress Gutenberg 可视化编辑器默认字体系列

如何解决如何更改 Wordpress Gutenberg 可视化编辑器默认字体系列

如何使我的网站主题字体与 wordpress Gutenberg 可视化编辑器认字体系列相同?

每次发布​​新帖子时,我的网站字体将认恢复为主题字体。

我想在 wordpress 中使用 Visual Editor 字体。如何做到这一点?

解决方法

如果我没记错的话,Gutenberg 默认字体基于您的操作系统。这种字体方法用于有效地重置浏览器的默认样式。

font-family: -apple-system,system-ui,BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue",Arial,sans-serif

一种可能的方法是使用 enqueue_block_editor_assets 动作钩子在编辑器内触发并覆盖 font-family 选择器。

我们可以使用 .editor-styles-wrapper 来覆盖同样的字体并将其设置为我们想要的任何值。

在以下示例中,我选择了 Ubuntu font-family from the Google Font website

现在当然要用于生产用途,您的字体将基于主题的字体。

<?php
/**
 * Fires after block assets have been enqueued for the editing interface.
 * @link https://developer.wordpress.org/reference/hooks/enqueue_block_editor_assets/
 * In the function call you supply,simply use wp_enqueue_script and wp_enqueue_style to add your functionality to the block editor.
*/
add_action( 'enqueue_block_editor_assets',function() {

    /**
     * Register & Enqueue gfont_css.
     * @link https://developer.wordpress.org/reference/functions/wp_enqueue_style/
    */
    wp_enqueue_style( 'gfont_css','https://fonts.googleapis.com/css2?family=Ubuntu:wght@400;700&display=swap',[],wp_get_theme()->version,'all' ); //... replace by any font,if your theme isn't using Google Font just enqueue a font font from your theme's directory instead and remove the data_gfont_css function below.

    /**
     * Add mandatory Google Font rel='preconnect' <link> and required attributes to gfont_css
     * Filters the HTML link tag of an enqueued style & add required attributes
     * @link https://developer.wordpress.org/reference/hooks/style_loader_tag/
     */
    add_filter( 'style_loader_tag','data_gfont_css',10,3 );
    function data_gfont_css( $tag,$handle,$src ) {
        if( $handle === 'gfont_css' ) {
            $tag = str_replace(
                "<link rel='stylesheet'","<link rel='preconnect' href='https://fonts.gstatic.com'>" . PHP_EOL . "<link rel='stylesheet'",$tag
            );
        };
        return $tag;
    };

} );

/**
 * Fires in head section for all admin pages.
 * Overwrite default Wordpress Gutenberg default font-familly.
 * @link https://developer.wordpress.org/reference/hooks/admin_head/
 */
add_action( 'admin_head',function() {

    /**
     * Get the current screen object.
     * If the screen object is the Gutenberg editor then inject our overwrite.
     * @link https://developer.wordpress.org/reference/functions/get_current_screen/
     */
    if ( get_current_screen()->is_block_editor() )
        echo "<style>.editor-styles-wrapper{font-family:'Ubuntu',sans-serif!important}</style>";
} );
?>

PHP > 7.1 需要,anonymous functions 使用。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。