簡體   English   中英

如何在古騰堡中使用序列化數據?

[英]How can I use serialized data in Gutenberg?

我正在嘗試創建一個側邊欄插件,用於存儲要在前端使用的帖子元數據。 在不涉及不必要的細節的情況下,我需要將所有數據存儲為 1 個元條目,而不是每個帖子的許多行 這是我到目前為止所擁有的:

// ds-jars.js

const pluginContent = (props) => {

    const productData = () => {
        const categoryId = createElement( PanelRow, null, 
            createElement(TextControl, {
                label: "Category Name",
                value: props.category_id,
                onChange: (content) => {
                    props.set_category_id(content)
                },
            })
        )
        const serialId = createElement( PanelRow, null, 
            createElement( TextControl, {
                label: "Serial Number",
                value: props.serial_id,
                onChange: (content) => { 
                    props.set_serial_id(content)
                }
            })
        )
        const productId = createElement( PanelRow, null, 
            createElement( TextControl, {
                label: "Product ID",
                value: props.product_id,
                onChange: (content) => { 
                    props.set_product_id(content)
                }
            })
        )

        return createElement(PluginDocumentSettingPanel, {
            title: "Product Data",
            name: "ds-jars-productdata",
            icon: 'none',
        }, categoryId, serialId, productId
        )
    }

    return productData()
}

const selectData = (select) => {
    return { 
        category_id:        select("core/editor").getEditedPostAttribute("meta")["category_id"],
        serial_id:          select("core/editor").getEditedPostAttribute("meta")["serial_id"],
        product_id:         select("core/editor").getEditedPostAttribute("meta")["product_id"],
        name:               select("core/editor").getEditedPostAttribute("meta")["name"],
        quantity:           select("core/editor").getEditedPostAttribute("meta")["quantity"],
        color:              select("core/editor").getEditedPostAttribute("meta")["color"],
        height:             select("core/editor").getEditedPostAttribute("meta")["height"],
        width:              select("core/editor").getEditedPostAttribute("meta")["width"],
        depth:              select("core/editor").getEditedPostAttribute("meta")["depth"],
        pattern:            select("core/editor").getEditedPostAttribute("meta")["pattern"],
        date_made:          select("core/editor").getEditedPostAttribute("meta")["date_made"],
        date_updated:       select("core/editor").getEditedPostAttribute("meta")["date_updated"],
        date_expired:       select("core/editor").getEditedPostAttribute("meta")["date_expired"]
    }
}

const dispatchData = (dispatch) => {
    return {
        set_category_id:    (value) => {dispatch("core/editor").editPost({meta:{category_id: value} })},
        set_serial_id:      (value) => {dispatch("core/editor").editPost({meta:{serial_id: value} })},
        set_product_id:     (value) => {dispatch("core/editor").editPost({meta:{product_id: value} })},
        set_name:           (value) => {dispatch("core/editor").editPost({meta:{name: value} })},
        set_quantity:       (value) => {dispatch("core/editor").editPost({meta:{quantity: value} })},
        set_color:          (value) => {dispatch("core/editor").editPost({meta:{color: value} })},
        set_height:         (value) => {dispatch("core/editor").editPost({meta:{height: value} })},
        set_width:          (value) => {dispatch("core/editor").editPost({meta:{width: value} })},
        set_depth:          (value) => {dispatch("core/editor").editPost({meta:{depth: value} })},
        set_pattern:        (value) => {dispatch("core/editor").editPost({meta:{pattern: value} })},
        set_date_made:      (value) => {dispatch("core/editor").editPost({meta:{date_made: value} })},
        set_date_updated:   (value) => {dispatch("core/editor").editPost({meta:{date_updated: value} })},
        set_date_expired:   (value) => {dispatch("core/editor").editPost({meta:{date_expired: value} })}
    }
}

let fieldSelect = withSelect(selectData)(pluginContent)
let fieldDispatch = withDispatch(dispatchData)(fieldSelect)

registerPlugin( "ds-jars", {
    icon: 'store',
    render: fieldDispatch 
})

顯然這可行,但將每個字段保存為它自己的元行條目。 根據這篇文章: WP 5.3 Supports Object and Array Meta Types in the REST API 我應該能夠通過為“show_in_rest”使用數組 in 將 object 發送到元字段。 我已經能夠使用以下方法正確注冊我想要的字段:

register_post_meta('', 'ds_product', 
            array(
                'type' => 'object',
                'single' => true,
                'show_in_rest' => array(
                    'schema' => array(
                        'type' => 'object',
                        'properties' => array(
                            'category_id'   => array('type' => 'string'),
                            'serial_id'     => array('type' => 'string'),
                            'product_id'    => array('type' => 'string'),
                            'name'          => array('type' => 'string'),
                            'quantity'      => array('type' => 'string'),
                            'color'         => array('type' => 'string'),
                            'height'        => array('type' => 'string'),
                            'width'         => array('type' => 'string'),
                            'depth'         => array('type' => 'string'),
                            'pattern'       => array('type' => 'string'),
                            'date_made'     => array('type' => 'string'),
                            'date_updated'  => array('type' => 'string'),
                            'date_expired'  => array('type' => 'string'),
                        )
                    )
                )
            )
        );

我可以通過 console.log 手動發送一個 object,因此它似乎已准備好將我的值作為 object 發送給它。我遇到的問題是使用 withSelect/withDispatch 函數寫入/讀取此元字段. 如何使用 withDispatch 將所有值發送到此元字段“ds_product”? 已經為此苦苦掙扎了一個星期。 我已經嘗試了很多東西,我最接近的是使用

// Create prop to get data from serialized field
category_id: select("core/editor").getEditedPostAttribute("meta")["ds_product"].category_id
category_id: select("core/editor").getEditedPostAttribute("meta")["ds_product"].serial_id
...

// Update serialized field
set_category_id: (value) => {dispatch("core/editor").editPost({meta:{ds_product:{category_id: value} }})},
set_serial_id: (value) => {dispatch("core/editor").editPost({meta:{ds_product:{serial_id: value} }})},
...

由於它們一次更新一個,因此該字段最終僅存儲先前更改的值,從而擦除它之前的所有其他數據。 任何幫助將不勝感激。 最后一點,我知道將序列化數據存儲到數據庫的危險/限制,但我仍然需要以這種方式完成。 提前致謝!

我遇到了這個問題,對我有用的是dispatch()saveEntityRecord的以下用法。

在下面的示例中,我將序列化的 object 保存到 WP 數據庫中的wp_options表中。

// Save serialized data to wp_options.
dispatch('core').saveEntityRecord('root', 'site', {
    my_plugin_settings: {
      test_1: 'Test 1 Setting Value',
      test_2: 'Test 1 Setting Value',
    },
  }).then(() => {

  })
  .catch((error) => {
    dispatch('core/notices').createErrorNotice('Error', {
      isDismissible: true,
      type: 'snackbar',
    });
  });
});

首先,您必須像上面那樣注冊設置,以便通過 REST API 可用。

register_setting(
        'my_plugin_settings',
        'my_plugin_settings',
        [
            'default'      => '',
            'show_in_rest' => [
                'schema' => [
                    'type'       => 'object',
                    'properties' => [
                        'test_1' => [
                            'type' => 'string',
                        ],
                        'test_2'                 => [
                            'type' => 'string',
                        ],
                    ]
                ],
            ]
        ]
    );

然后使用上面我的答案中的代碼,您可以正確保存序列化值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM