Render Page Custom Field Data in Gutenberg Block
- This topic has 5 replies, 2 voices, and was last updated 4 years ago by
Kyle Melton.
-
AuthorPosts
-
October 5, 2021 at 10:32 PM #31165
Kyle Melton
ParticipantHi All,
I was wondering if there was a way to render the output of a text custom field into a Gutenberg block created with MB Blocks. To add context we used the twig option to create the Gutenberg blocks and we have a custom field that we would like to use as a setting in several blocks we have created without the user having to enter it for each block placed on the page.
Thanks!
October 6, 2021 at 9:20 AM #31174Long Nguyen
ModeratorHi Kyle,
You can use the helper function rwmb_meta() and pass the ID of the page/post as the third parameter to get
textfield value of that post/page.rwmb_meta( 'text_fieldID', '', 12345 );If you use the Render Code area in the Builder, call a PHP function via the proxy
mb. Please read more here https://docs.metabox.io/extensions/mb-views/#running-php-functionsOctober 9, 2021 at 9:05 PM #31242Kyle Melton
ParticipantThank you for your answer. So if I were to call it in code using the example like this:
{% set post = mb.get_post( 123 ) %} {{ post.post_title }}In my scenario my custom field has a field id of 3168
and my custom field name is product_nameUsing the above code in MB blocks code I could simply call it like this (if I am understanding that correctly):
{% set post = mb.get_post( 3168 ) %} {{ post.product_name }}It appears blank when I test it so I am sure I am missing one small simple piece.
Thanks again for all of your help!
October 9, 2021 at 10:07 PM #31246Kyle Melton
ParticipantPlease disregard my last post. I wound up getting it to work like this:
{% set post = mb.get_post() %} {{ post.product_name }}It renders my custom field on the front end from within a Gutenberg block but it does not show up in the editor. It is just a blank block. Any way to render here for preview?
October 9, 2021 at 11:10 PM #31248Long Nguyen
ModeratorHi Kyle,
If you do not pass the post ID to the function
get_post(), it only works only on the frontend.null, false, 0 and other PHP falsey values return the current global post inside the loopPlease read more on the documentation https://developer.wordpress.org/reference/functions/get_post/
The Render Code area in the Builder supports to get the current post ID by using the variable
post_id. For example:{% set post = mb.get_post( post_id ) %} {{ post.product_name }}List of prebuilt variables can be used:
attributeBlock attribute. Replace attribute with anchor, align, or className.
field_idField value. Replace field_id with a real field ID.
is_previewWhether in preview mode.
post_idCurrent post ID.October 28, 2021 at 1:48 AM #31561Kyle Melton
ParticipantThank you Long!
Much appreciated!
-
AuthorPosts
- You must be logged in to reply to this topic.