在Symfony中调用WordPress API获取文章时如何获取Gutenberg区块CSS?
获取Gutenberg区块CSS的解决方案
方法一:自定义WordPress API端点返回区块专属CSS
WordPress本身没有直接返回单篇文章区块CSS的API,需要自己在WP端添加自定义路由来生成并返回所需样式:
- 在WordPress主题的
functions.php中添加以下代码,注册自定义API路由:
add_action('rest_api_init', function () { register_rest_route('custom/v1', '/post-block-css/(?P<id>\d+)', [ 'methods' => 'GET', 'callback' => 'get_post_block_css', 'permission_callback' => '__return_true', // 生产环境建议根据需求设置权限验证 ]); }); function get_post_block_css($request) { $post_id = $request['id']; $post = get_post($post_id); if (!$post) { return new WP_Error('invalid_post', '文章不存在', ['status' => 404]); } // 生成当前文章区块的内联CSS $block_inline_css = ''; if (function_exists('wp_get_block_css')) { $blocks = parse_blocks($post->post_content); $block_inline_css = wp_get_block_css($blocks); } // 获取Gutenberg基础区块全局样式 wp_enqueue_style('wp-block-library'); global $wp_styles; $global_block_css = file_get_contents(home_url($wp_styles->registered['wp-block-library']->src)); // 可选:获取主题自定义的区块样式(如果主题有) $theme_block_css = ''; if (wp_style_is('wp-block-library-theme', 'registered')) { wp_enqueue_style('wp-block-library-theme'); $theme_block_css = file_get_contents(home_url($wp_styles->registered['wp-block-library-theme']->src)); } return [ 'inline_css' => $block_inline_css, 'global_css' => $global_block_css, 'theme_css' => $theme_block_css ]; }
- 在Symfony应用中调用这个自定义API,获取CSS后渲染到页面:
// 获取文章基础数据 $postData = json_decode(file_get_contents("http://localhost:8888/my-website/wp-json/wp/v2/posts/22328"), true); // 获取区块CSS数据 $cssResponse = json_decode(file_get_contents("http://localhost:8888/my-website/wp-json/custom/v1/post-block-css/22328"), true);
在Twig模板中引入样式:
{# 全局基础区块样式 #} <style>{{ cssResponse.global_css }}</style> {# 主题自定义区块样式 #} {% if cssResponse.theme_css %} <style>{{ cssResponse.theme_css }}</style> {% endif %} {# 当前文章专属的区块内联样式 #} <style>{{ cssResponse.inline_css }}</style> {# 渲染文章内容 #} <div class="entry-content">{{ postData.content.rendered|raw }}</div>
方法二:直接引入WordPress的区块样式文件
如果不需要单篇文章的专属内联样式,仅需基础Gutenberg区块样式,可以直接在Symfony页面中引入WP自带的区块样式文件:
在Twig模板中添加:
<link rel="stylesheet" href="http://localhost:8888/my-website/wp-includes/css/dist/block-library/style.min.css"> {# 可选:引入主题的区块样式(如果主题有) #} <link rel="stylesheet" href="http://localhost:8888/my-website/wp-content/themes/[你的主题名]/style.css">
这种方式简单直接,但无法获取单篇文章中自定义区块的内联样式(比如区块的自定义间距、颜色等),适合只需要基础样式的场景。
内容的提问来源于stack exchange,提问作者Benjamin de Monchy
相关产品推荐
相关产品推荐

