You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Gutenberg区块的Edit.js文件中获取WordPress Options?

在Gutenberg区块Edit.js中获取WordPress选项的两种方法

在Gutenberg前端脚本中无法直接调用PHP的get_option(),但可以通过以下两种常用方式实现:

方法一:通过wp_localize_script传递选项到前端

这种方式适合在区块加载时就需要获取选项值的场景,直接将PHP端的选项数据注入到前端脚本中。

1. 在区块注册的PHP文件中添加代码

// 获取目标选项值,第二个参数是默认值
$target_option = get_option('option_name', '默认内容');

// 注册区块的前端脚本
wp_register_script(
    'custom-block-script',
    get_template_directory_uri() . '/blocks/custom-block/Edit.js',
    array('wp-blocks', 'wp-element'),
    filemtime(get_template_directory() . '/blocks/custom-block/Edit.js')
);

// 将选项数据传递到前端,定义全局可访问的变量
wp_localize_script(
    'custom-block-script',
    'BlockGlobalData', // 前端全局变量名,注意避免命名冲突
    array(
        'targetOption' => $target_option,
    )
);

wp_enqueue_script('custom-block-script');

2. 在Edit.js中调用全局变量

import { useBlockProps } from '@wordpress/block-editor';

export default function Edit() {
    const blockProps = useBlockProps();
    // 直接访问传递过来的选项值
    const optionValue = window.BlockGlobalData.targetOption;

    return (
        <div {...blockProps}>
            <p>获取到的选项值:{optionValue}</p>
        </div>
    );
}

方法二:通过自定义REST API端点获取选项

如果需要动态获取选项(比如选项可能在区块加载后更新),可以通过REST API请求获取。

1. 在PHP中注册自定义REST路由

add_action('rest_api_init', function () {
    register_rest_route(
        'custom-block/v1',
        '/option/',
        array(
            'methods' => 'GET',
            'callback' => 'custom_block_get_option',
            // 权限验证:仅允许有编辑权限的用户访问
            'permission_callback' => function () {
                return current_user_can('edit_posts');
            },
        )
    );
});

function custom_block_get_option($request) {
    $option_name = $request->get_param('name');
    if (empty($option_name)) {
        return new WP_Error('missing_param', '缺少选项名称参数', array('status' => 400));
    }
    // 返回选项值,自动转为REST响应格式
    return rest_ensure_response(get_option($option_name, ''));
}

2. 在Edit.js中发起API请求

import { useBlockProps } from '@wordpress/block-editor';
import { useEffect, useState } from '@wordpress/element';
import apiFetch from '@wordpress/api-fetch';

export default function Edit() {
    const blockProps = useBlockProps();
    const [optionValue, setOptionValue] = useState('');

    useEffect(() => {
        // 发起API请求获取指定选项
        apiFetch({
            path: '/custom-block/v1/option/?name=option_name',
            method: 'GET',
        })
        .then(response => {
            setOptionValue(response);
        })
        .catch(error => {
            console.error('获取选项失败:', error);
        });
    }, []);

    return (
        <div {...blockProps}>
            <p>获取到的选项值:{optionValue}</p>
        </div>
    );
}

内容的提问来源于stack exchange,提问作者Amrit Ray

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 23:30:00