首先我下载了 https://carbonfields.net/zip/latest/并在 WP 后端安装了插件。我也激活了它。
对于这个测试用例,我使用“Twenty Sixteen”模板和全新的 WordPress 安装,没有安装任何其他插件,根据Carbon Fields 的文档页面,我将以下代码添加到我的 functions.php 文件的顶部:
<?php // PHP 7
use Carbon_Fields\Container;
use Carbon_Fields\Field;
add_action( 'carbon_fields_register_fields', 'crb_attach_theme_options' );
function crb_attach_theme_options() {
Container::make( 'theme_options', 'Theme Options' )
-> set_page_menu_position( 0 )
-> add_fields( array(
Field::make( 'text', 'crb_text')
) );
}
到目前为止一切看起来都很好,因为“主题选项”正如预期的那样出现在 WP 后端。
现在我尝试crb_text
按如下方式检索字段值:
// this snippet starts exactly where the previous one ended
add_action( 'after_setup_theme', 'crb_load' );
function crb_load() {
// require_once( ABSPATH . '/vendor/autoload.php' ); original from website throws: "Failed opening required" so modified to:
require_once( ABSPATH . 'wp-content/plugins/carbon-fields/vendor/autoload.php' );
\Carbon_Fields\Carbon_Fields::boot();
var_dump( carbon_get_theme_option( 'crb_text' ) ); // -> string(0) ""
var_dump( carbon_get_theme_option( '_crb_text' ) ); // -> string(0) "" isn't actually the right way to do it but give it a try for testing purpose
var_dump( get_option( '_crb_text' ) ); // -> string(4) "test"
}
如您所见,我可以通过调用get_option( '_crb_text' )
原生 WP 方式来检索数据,但插件功能carbon_get_theme_option( 'crb_text' )
不起作用。carbon_get_theme_option()
实际上,这对于“简单字段”来说很好,但是在这种情况下,插件自己的函数必须检索“复杂字段” 。
我也确实看过这个问题:use Carbon Fields in custom plugin class。但是这个问题在我开始的地方结束。
先感谢您...
PS:我习惯使用 Carbon Fields 1.6,它可以在非常相似的设置下正常工作,但想升级到分支 2。
我的环境又是:define('WP_DEBUG', true);
,Carbon Fields 2.1.0,WordPress 4.8.2–de_DE(全新安装,除了 Carbon Fields 之外没有其他插件),二十六个 1.3,PHP 7