Carbon Fields - 所选术语与帖子无关

问题描述 投票:0回答:2

我开始使用 Carbon Fields(与 Wordpress),但遇到了问题。

  1. 我在本地主机上安装了 Wordpress v.6.0.1(Windows 10、OpenServer、PHP 8.0、MySQl 8.0);
  2. 然后我使用composer安装了Carbon Fields。
  3. 我创建了多个类别和一篇帖子。
  4. 我使用 Carbon Fields 创建了一个关联字段,以从该字段中选择帖子类别
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();
}

image 1

  1. 选择类别1并保存帖子后,该类别与帖子不再关联。 image 2 image 3

  2. 如果我在侧边栏中选择一个类别,它就可以正常工作。 image 4

  3. 有什么问题吗?怎么解决?

wordpress carbon-fields
2个回答
0
投票

您混合了两个看似相关的主题:

  1. worpress 上的类别
  2. CarbonFields 上的关联关系。

如图 4 所示的类别的前侧右侧面板由 WordPress 以及您创建的

count
列进行管理。即使当您将关联碳字段与类别术语一起使用时,您也会获得与 WordPress 使用的相同的卡路里列表,当您保存帖子时,碳字段会将此关系存储在其自己的字段中,因此 Worpress 不会收到您选择的通知这些类别是因为 Wordpres 与其他自定义字段类似。

总而言之,类别术语是由 WordPress 存储和管理的,而您与 CarbonFields 创建的关联是由您自己管理的。


0
投票

我也为此苦苦挣扎,遗憾的是它不会自动发生。他们可以在字段定义中为其提供一个参数来实现这一点。

下面的代码应该可以工作。

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);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.