SOLVED: Issue with custom meta field in Bricks Builder

Browser: Chrome 110
OS: macOS / Windows / Linux / etc.
URL: Quarto MC – Sala 106 ®
Video: https://youtu.be/fpb8LQz9MoQ

Recently, we implemented a gallery metabox in our posts using custom code in WordPress.

The issue we are encountering is that, although the dynamic data associated with the gallery metabox is available in WordPress (identified as {cf_gallery_images}), we are unable to access it in Bricks Builder. We cannot find the custom_gallery_images dynamic field associated with the gallery metabox when attempting to configure the carousel module in Bricks Builder to display these dynamic images.

Additionally, when selecting the {cf_gallery_images} dynamic field within the Bricks Builder carousel module, it only presents the first image of the gallery, instead of displaying all images from the gallery.

We are confident that the image IDs are being saved correctly in the gallery metabox, as we are able to access and confirm them in WordPress. However, even with the correct IDs available, we are unable to display the corresponding images on the frontend using Bricks Builder.

Would it be possible to check why the dynamic data associated with the gallery metabox is not being recognized or available in Bricks Builder? Is there any additional step we need to follow to ensure that the dynamic data is properly integrated into Bricks Builder?

//Gallery metabox code:
// Adicionar o Metabox
function add_custom_metabox() {
    add_meta_box(
        'custom_metabox', // ID do metabox
        'Image Gallery', // Título do metabox
        'custom_metabox_callback', // Função de callback
        'post', // Tipo de post onde aparecerá
        'normal', // Contexto
        'high' // Prioridade
    );
}
add_action('add_meta_boxes', 'add_custom_metabox');

// Callback do Metabox
function custom_metabox_callback($post) {
    wp_nonce_field(basename(__FILE__), 'custom_metabox_nonce');
    $stored_meta = get_post_meta($post->ID);
?>
    <div>

        <input type="hidden" id="gallery_images" name="gallery_images" value="<?php echo esc_attr(get_post_meta($post->ID, 'gallery_images', true)); ?>" />
        <button type="button" id="upload_gallery_button" class="button"><span class="dashicons dashicons-format-gallery" style="font: normal 18px / 1 dashicons;
    line-height: 28px;"></span> Add Imagens</button>
        <div id="gallery_images_container" class="sortable">
            <?php
            $image_ids = get_post_meta($post->ID, 'gallery_images', true);
            if (!empty($image_ids)) {
                $image_ids = explode(',', $image_ids);
                foreach ($image_ids as $image_id) {
                    $image_url = wp_get_attachment_image_src($image_id, 'thumbnail');
                    echo '<div class="gallery-image" data-image-id="' . esc_attr($image_id) . '"><img src="' . esc_url($image_url[0]) . '" /><a href="#" class="remove-image">Remove</a></div>';
                }
            }
            ?>
        </div>
    </div>

    <script>
        jQuery(document).ready(function($) {
            var frame;
            $('#upload_gallery_button').on('click', function(e) {
                e.preventDefault();
                if (frame) {
                    frame.open();
                    return;
                }
                frame = wp.media({
                    title: 'Selecione ou envie suas imagens',
                    button: { text: 'Usar estas imagens' },
                    multiple: true
                });
                frame.on('select', function() {
                    var attachments = frame.state().get('selection').toJSON();
                    var image_ids = [];
                    attachments.forEach(function(attachment) {
                        image_ids.push(attachment.id);
                        $('#gallery_images_container').append('<div class="gallery-image" data-image-id="' + attachment.id + '"><img src="' + attachment.sizes.thumbnail.url + '" /><a href="#" class="remove-image">Remove</a></div>');
                    });
                    $('#gallery_images').val(image_ids.join(','));
                });
                frame.open();
            });

            // Inicializar a funcionalidade de arrastar e soltar
            $('#gallery_images_container').sortable({
                update: function(event, ui) {
                    var image_ids = [];
                    $(this).children('.gallery-image').each(function() {
                        image_ids.push($(this).data('image-id'));
                    });
                    $('#gallery_images').val(image_ids.join(','));
                }
            });

            // Remover imagem
            $(document).on('click', '.remove-image', function(e) {
                e.preventDefault();
                $(this).parent().remove();
                var image_ids = [];
                $('#gallery_images_container').children('.gallery-image').each(function() {
                    image_ids.push($(this).data('image-id'));
                });
                $('#gallery_images').val(image_ids.join(','));
            });
        });
    </script>
    <style>
		#poststuff .inside {
			margin: 10px 0 0;
		}
        .gallery-image {
            display: inline-block;
            margin-right: 10px;
            cursor: move;
        }
        .gallery-image img {
            display: block;
			margin-top: 10px;
            max-width: 100px;
            height: auto;
        }
        .gallery-image a {
            display: block;
            text-align: center;
            margin-top: 5px;
            color: #b32d2e;
        }
    </style>
<?php
}

// Salvar os Metadados
function save_custom_metabox($post_id) {
    if (!isset($_POST['custom_metabox_nonce']) || !wp_verify_nonce($_POST['custom_metabox_nonce'], basename(__FILE__))) {
        return $post_id;
    }
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
        return $post_id;
    }
    if (!current_user_can('edit_post', $post_id)) {
        return $post_id;
    }
    if (isset($_POST['gallery_images'])) {
        update_post_meta($post_id, 'gallery_images', sanitize_text_field($_POST['gallery_images']));
    } else {
        delete_post_meta($post_id, 'gallery_images');
    }
}
add_action('save_post', 'save_custom_metabox');


//Gallery dynamic data code
	function bricks_custom_gallery_dynamic_data() {
    if (function_exists('bricks_register_dynamic_data')) {
        bricks_register_dynamic_data('custom_gallery_images', [
            'title' => 'Custom Gallery Images',
            'description' => 'Dynamic data for custom gallery images.',
            'callback' => function() {
                global $post;
                $image_ids = get_post_meta($post->ID, 'gallery_images', true);
                $images = [];
                if ($image_ids) {
                    $image_ids = explode(',', $image_ids);
                    foreach ($image_ids as $image_id) {
                        $image_url = wp_get_attachment_image_src($image_id, 'full');
                        $images[] = [
                            'id' => $image_id,
                            'url' => $image_url[0],
                        ];
                    }
                }
                return $images;
            },
        ]);
    }
}
add_action('bricks_init', 'bricks_custom_gallery_dynamic_data');

Hi @olucasparra ,

Bricks will not process/transform any dynamic tag starting with cf_ to suit different context or elements.

You can try output {cf_gallery_images} in a basic text element and check what is the data first.
It’s not possible to handle every single custom field created by different plugins or developers and accurately convert to a suitable data to be used on different element. (Except those native integrations like ACF, Metabox.io, JetEngine etc.)

For your case, you can create a custom PHP function to retrieve the data and transform it to an array of attachment IDs. Then you should be able to use it on the carousel element.

Example: (remember to add my_custom_image_field function to bricks/code/echo_function_names)

function my_custom_image_field() {
  // retrieve your field data
  // ensure to return attachment IDs in an array
  return [11749,11748];
}

Then use {echo:my_custom_image_field} on the carousel element will do.

I moved this thread to developer category.

Regards,
Jenn

1 Like

@itchycode, thanks for your help.

I used the following codes and worked:

função personalizada no seu tema ou plugin:
function my_custom_image_field() {
global $post;
$image_ids = get_post_meta($post->ID, ‘gallery_images’, true);
if (!empty($image_ids)) {
return explode(‘,’, $image_ids);
}
return ;
}

and

função à lista de funções permitidas no Bricks Builder:

add_filter(‘bricks/code/echo_function_names’, function($functions) {
$functions = ‘my_custom_image_field’;
return $functions;
});