我开始使用 Carbon Fields(与 Wordpress),但遇到了问题。
use Carbon_Fields\Container;
use Carbon_Fields\Field;
add_action( 'carbon_fields_register_fields', 'crb_attach_post_fields' );
function crb_attach_post_fields() {
Container::make( 'post_meta', 'Post settings' )
->where( 'post_type', '=', 'post' )
->add_fields( array(
Field::make( 'association', 'crb_category', 'Category' )
->set_types( array(
array(
'type' => 'term',
'taxonomy' => 'category',
)
) )
));
}
add_action( 'after_setup_theme', 'crb_load' );
function crb_load() {
require_once( 'vendor/autoload.php' );
\Carbon_Fields\Carbon_Fields::boot();
}
您混合了两个看似相关的主题:
如图 4 所示的类别的前侧右侧面板由 WordPress 以及您创建的
count
列进行管理。即使当您将关联碳字段与类别术语一起使用时,您也会获得与 WordPress 使用的相同的卡路里列表,当您保存帖子时,碳字段会将此关系存储在其自己的字段中,因此 Worpress 不会收到您选择的通知这些类别是因为 Wordpres 与其他自定义字段类似。
总而言之,类别术语是由 WordPress 存储和管理的,而您与 CarbonFields 创建的关联是由您自己管理的。
我也为此苦苦挣扎,遗憾的是它不会自动发生。他们可以在字段定义中为其提供一个参数来实现这一点。
下面的代码应该可以工作。
add_action('carbon_fields_post_meta_container_saved', 'save_taxonomies_to_categories', 10, 2);
function save_bnc_taxonomies_to_categories($post_id, $container) {
$association_field = "crb_category";//your association field
$custom_tax = "category"; //your taxonomy
// Check if this is an autosave
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
return;
}
// Check if current user can edit post
if (!current_user_can('edit_post', $post_id)) {
return;
}
$bnc_terms = carbon_get_post_meta($post_id, $association_field);
$terms = [];
if (is_array($bnc_terms) && count($bnc_terms)) {
foreach ($bnc_terms as $term) {
$terms[] = (INT) $term['id'];
}
// Update post categories with BNC terms
wp_set_object_terms($post_id, $terms, $custom_tax);
} else {
wp_set_object_terms($post_id, [], $custom_tax);
}
}