block editor - Gutenberg: Dynamic rendering of RichText

admin2025-01-08  8

When I save <RichText />s content into my attributes and want to use this with render_callback in php, it get's kinda messy. As soon as the text contains RichText (bold, italic, line-breaks etc.), $attributes stores it really complicated

attributes: {
    description: {
        type: "text",
        // no source, so it goes straight into the html comment, nice for dynamic rendering
    }
}


...
"render_callback" => function( $attributes ) {
    return "<p>" . $attributes["description"] . "</p>"
}


// var_dump($attributes["description"]
array(3) {
    [0]=>
    string(24) "Rendering RichText with "
    [1]=>
    array(5) {
      ["type"]=>
      string(6) "strong"
      ["key"]=>
      string(10) "_domReact4"
      ["ref"]=>
      NULL
      ["props"]=>
      array(1) {
        ["children"]=>
        string(3) "php"
      }
      ["_ower"]=>
      NULL
    }
    [2]=>
    string(22) " is a pain in the a..."
  }

I guess there is a reason why they save RichText like this. Question now is:

How can I use it when rendering dynamically? Is there some function I don't know of? Like: wp_decode_richtext()

When I save <RichText />s content into my attributes and want to use this with render_callback in php, it get's kinda messy. As soon as the text contains RichText (bold, italic, line-breaks etc.), $attributes stores it really complicated

attributes: {
    description: {
        type: "text",
        // no source, so it goes straight into the html comment, nice for dynamic rendering
    }
}


...
"render_callback" => function( $attributes ) {
    return "<p>" . $attributes["description"] . "</p>"
}


// var_dump($attributes["description"]
array(3) {
    [0]=>
    string(24) "Rendering RichText with "
    [1]=>
    array(5) {
      ["type"]=>
      string(6) "strong"
      ["key"]=>
      string(10) "_domReact4"
      ["ref"]=>
      NULL
      ["props"]=>
      array(1) {
        ["children"]=>
        string(3) "php"
      }
      ["_ower"]=>
      NULL
    }
    [2]=>
    string(22) " is a pain in the a..."
  }

I guess there is a reason why they save RichText like this. Question now is:

How can I use it when rendering dynamically? Is there some function I don't know of? Like: wp_decode_richtext()

Share Improve this question asked Jun 18, 2018 at 9:06 kater louiskater louis 2802 silver badges13 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 0

The attribute in question should have the type of "string" so that it would be rendered properly.

attributes: {
    description: {
        type: "string",
    }
}
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1736265889a1077.html

最新回复(0)