• mxkyb

    (@maxkieltyka)


    Hello,

    I am trying to save some meta data on a block used exclusively inside templates. But it seems like there is not data saved back to the database. Did I get something wrong from the documentation?

    
    // functions.php
    function myguten_register_post_meta() {
        register_post_meta('wp_template', 'test_meta_field', [
            'show_in_rest' => true,
            'single' => true,
            'type' => 'string',
            'default' => 'baz bar',
        ]);
    }
    
    add_action('init', 'myguten_register_post_meta');
    
    // block edit render function
    const [meta, setMeta] = useEntityProp('postType', 'wp_template', 'meta');
    
    const updateMetaValue = () => {
        setMeta({
            test_meta_field: 'foobar test',
        });
    };
    
    console.log({meta});
    
    useEffect(() => {
        console.log('run update meta');
    
        updateMetaValue();
    }, []);
    
Viewing 1 replies (of 1 total)
  • Thread Starter mxkyb

    (@maxkieltyka)

    I think the problem is related to nonce permissions. Not sure though.

    I ended up implementing it differently.

    // block.json
    // ...
    "attributes": {
      "teasers": {
        "type": "object",
        "default": {}
      }
    },
    // ...
    // edit.js
    useEffect(() => {
        setAttributes({
            teasers,
        });
    }, [teasers]);
    
    // functions.php simplified
    $templates = get_block_templates();
    
    foreach ($templates as $template) {
        if ($template->slug === $slug) {
            return $template;
        }
    }
    
    $content = $template->content;
    $blocks = parse_blocks($content);
    $mainBlock = $blocks[0];
    
    $teasers = $mainBlock['attrs']['teasers'];
    
    var_dump($teasers);
Viewing 1 replies (of 1 total)
  • The topic ‘register_post_meta for wp_template’ is closed to new replies.