-
Guillermo
Hi, I’ve created a template where I add a collection of elements (products) with a link like this:
<a href="javascript:void(0);" class="quick-view-btn" data-product-id="<?php echo get_the_ID(); ?>">+ INFO PRODUCTO</a>
when you click on the link it shows a popup window that show a bunch of content from ACF.
I’ve created a block element to show that elments from ACF, but I have no idea how to get that product_id to get that content fields.
I have tried, <?php do_action(‘hook_acordeon’, $product_id); ?>, but it’s not working.Any idea how can I use the block with dynamic id?.
Thanks.
-
Hi there,
but I have no idea how to get that product_id to get that content fields.
Where are you going to use the product id? It’s not in your link HTML.
Not sure what you are trying to achieve, can you explain some more? Or can I see what you’ve done on your site to have a better understanding?
Let me know 🙂
-
Guillermo
I’ve created a plugin that adds this piece of code in single-product and a popup.
$product_id = intval($_POST['product_id']); <div class="contenedor acordeon"> <?php do_action('hook_acordeon', $product_id); ?> </div>
hook_acordeon is a block element with dynamic data from ACF and Data Source: Current post.
When I you check the single product, single product it works fine because it gets the current post id (I guess).
But when I use it on the template with more than one product (id), it doesn’t shows the block.
On the main page, if you click on a product and click on “+ INFO PRODUCTO” it shows a popup, in that popup I have added the code, but as you can see it’s not showing the accordion.I hope I have explain myself better
-
It’s hard to tell, try adding some debug code to your code.
1. Add some debugging code to your code:
$product_id = isset($_POST['product_id']) ? intval($_POST['product_id']) : 0; error_log('Popup Product ID: ' . $product_id); error_log('Post Exists: ' . (get_post($product_id) ? 'Yes' : 'No')); error_log('ACF Fields: ' . print_r(get_fields($product_id), true)); ?> <div class="contenedor acordeon"> <?php do_action('hook_acordeon', $product_id); ?> </div>
2. Enable WP debug.
Let me know what you get in the debug log.
-
Guillermo
Hi,
I must not have explained correctly.
In the template there is no problem to obtain the produc_id. Anyway this is the debug:[13-Apr-2025 16:57:10 UTC] Popup Product ID: 1104 [13-Apr-2025 16:57:10 UTC] Post Exists: Yes [13-Apr-2025 16:57:10 UTC] ACF Fields: Array ( [produccion_estimada] => 500 [fecha_estimada_plantacion] => 15/05/2025 [fecha_de_entrega_estimada] => 28/03/2025 [que_recibes] => <p><span style="font-weight: 400;">En </span><b>Oliete (Teruel), la tierra vuelve a contar historias</b><span style="font-weight: 400;"> a través de los frutos de sus huertas. Cada ingrediente de este pisto proviene de huertas recuperadas donde la agricultura tradicional sigue viva. </span><b>Tomates, calabacines, berenjena, cebollas y pimientos</b><span style="font-weight: 400;"> crecen bajo el sol, madurando a su ritmo natural, sin prisas y sin artificios.</span></p> <p><strong>Sin azúcar ni sal añadidos</strong>, este pisto es una opción más natural y saludable. El sabor lo pone la huerta. Si quieres, añade tu toque al servirlo: sal, especias… o incluso un poco de miel.</p> <p><span style="font-weight: 400;">Disfrútalo caliente o frío, sobre una buena rebanada de pan, como guarnición o como base de un buen plato casero. Nuestro pisto de verduras sabe a hogar.</span></p> <p><span style="font-weight: 400;">📅 </span><b>Fecha de consumo</b><span style="font-weight: 400;">: 2 años.</span></p> <p><span style="font-weight: 400;">📦 </span><b>Cada caja contiene 9 tarros de pisto de verduras de 320 g cada uno.</b></p> [el_hortelano] => <p><img src="https://test.somosdelpueblo.com/wp-content/uploads/2025/02/MISAEL-300x300.jpg" alt="" width="300" height="300" /></p> <ul> <li><strong>Nombre: </strong><span style="font-weight: 400;">Misael</span></li> <li><strong>Descripción</strong><strong>:</strong> Misael conoce la huerta perfectamente y también todas las amenazas que sobre ella se ciernen, se anticipa a las plagas y, gracias a él, el cultivo está siempre seguro.</li> </ul> [fases_de_tu_mecenazgo] => Array ( [ID] => 890 [id] => 890 [title] => Pimiento: Fases de tu mecenazgo [filename] => PIMIENTO.jpg [filesize] => 113017 [url] => http://somos-del-pueblo.local/wp-content/uploads/2025/03/PIMIENTO.jpg [link] => http://somos-del-pueblo.local/?attachment_id=890#main [alt] => Pimiento: Fases de tu mecenazgo [author] => 2 [description] => Pimiento: Fases de tu mecenazgo [caption] => Pimiento: Fases de tu mecenazgo [name] => enero-3-2 [status] => inherit [uploaded_to] => 809 [date] => 2025-03-20 13:14:27 [modified] => 2025-03-20 13:15:07 [menu_order] => 0 [mime_type] => image/jpeg [type] => image [subtype] => jpeg [icon] => http://somos-del-pueblo.local/wp-includes/images/media/default.png [width] => 1920 [height] => 601 [sizes] => Array ( [thumbnail] => http://somos-del-pueblo.local/wp-content/uploads/2025/03/PIMIENTO-150x150.jpg [thumbnail-width] => 150 [thumbnail-height] => 150 [medium] => http://somos-del-pueblo.local/wp-content/uploads/2025/03/PIMIENTO-300x94.jpg [medium-width] => 300 [medium-height] => 94 [medium_large] => http://somos-del-pueblo.local/wp-content/uploads/2025/03/PIMIENTO-768x240.jpg [medium_large-width] => 768 [medium_large-height] => 240 [large] => http://somos-del-pueblo.local/wp-content/uploads/2025/03/PIMIENTO-1024x321.jpg [large-width] => 1024 [large-height] => 321 [1536x1536] => http://somos-del-pueblo.local/wp-content/uploads/2025/03/PIMIENTO-1536x481.jpg [1536x1536-width] => 1200 [1536x1536-height] => 376 [2048x2048] => http://somos-del-pueblo.local/wp-content/uploads/2025/03/PIMIENTO.jpg [2048x2048-width] => 1200 [2048x2048-height] => 376 [woocommerce_thumbnail] => http://somos-del-pueblo.local/wp-content/uploads/2025/03/PIMIENTO-300x225.jpg [woocommerce_thumbnail-width] => 300 [woocommerce_thumbnail-height] => 225 [woocommerce_single] => http://somos-del-pueblo.local/wp-content/uploads/2025/03/PIMIENTO-600x188.jpg [woocommerce_single-width] => 600 [woocommerce_single-height] => 188 [woocommerce_gallery_thumbnail] => http://somos-del-pueblo.local/wp-content/uploads/2025/03/PIMIENTO-100x100.jpg [woocommerce_gallery_thumbnail-width] => 100 [woocommerce_gallery_thumbnail-height] => 100 ) ) [fecha_inicio_preventa] => [fecha_fin_preventa] => [la_huerta] => <ul> <li style="font-weight: 400;" aria-level="1"><strong>Nombre</strong><span style="font-weight: 400;"><strong>: </strong> La vega</span></li> <li style="font-weight: 400;" aria-level="1"><strong>Superficie</strong><span style="font-weight: 400;"><strong>:</strong> 1.200 m2</span></li> <li style="font-weight: 400;" aria-level="1"><strong>Ubicación</strong><span style="font-weight: 400;"><strong>:</strong> Oliete (Teruel)</span></li> <li style="font-weight: 400;" aria-level="1"><strong>Cultivos</strong><span style="font-weight: 400;"><strong>:</strong> Pimiento</span></li> <li style="font-weight: 400;" aria-level="1"><strong>Técnicas de cultivo:</strong><span style="font-weight: 400;"> Reconversión a agricultura ecológica</span></li> <li><strong>Sistema de riego:</strong><span style="font-weight: 400;"> Inundación y goteo en 2026</span></li> </ul> <p> </p> <ul> <li style="font-weight: 400;" aria-level="1"><strong>Nombre</strong><span style="font-weight: 400;"><strong>:</strong> Capellanía</span></li> <li style="font-weight: 400;" aria-level="1"><strong>Superficie</strong><span style="font-weight: 400;"><strong>:</strong> 6.000 m2</span></li> <li style="font-weight: 400;" aria-level="1"><strong>Ubicación</strong><span style="font-weight: 400;"><strong>:</strong> Alacón (Teruel)</span></li> <li style="font-weight: 400;" aria-level="1"><strong>Cultivos</strong><span style="font-weight: 400;"><strong>:</strong> Tomate</span></li> <li style="font-weight: 400;" aria-level="1"><strong>Técnicas de cultivo:</strong><span style="font-weight: 400;"> Reconversión a agricultura ecológica</span></li> <li><strong>Sistema de riego:</strong><span style="font-weight: 400;"> Goteo</span></li> </ul> )
the problem is when passing the id to the hook to display the element(which is using dynamic data).
Can it be a problem of how the element is configured?
Thank!
-
Hi there,
try wrapping the hook in a loop that queries the product ID.
This should provide the context for the element to which the post meta values can be retrieved.<?php $product_id = intval($_POST['product_id']); // Validate $product_id if ($product_id && get_post($product_id)) { // Set up a WP_Query for the specific product_id $query = new WP_Query([ 'p' => $product_id, 'post_type' => 'any', // Adjust to 'product' if using WooCommerce, etc. 'posts_per_page' => 1, ]); if ($query->have_posts()) : while ($query->have_posts()) : $query->the_post(); ?> <div class="contenedor acordeon"> <?php do_action('hook_acordeon'); ?> </div> <?php endwhile; // Reset post data to avoid conflicts wp_reset_postdata(); else : echo '<p>Product not found.</p>'; endif; } else { echo '<p>Invalid product ID.</p>'; } ?>
-
Guillermo
I’m afraid it’s also not working.
Is there a way to log the block-hook (hook_acorden) element and see if the id is in there?.Thanks.
-
How is the modal request being made ? Is it an AJAX request or something ?
-
Guillermo
Hi,
when you click on +INFO the popup is created on ajax using the function “obtener_info_producto”.// Abrir el popup al hacer clic en el botón "Quick View" $(document).on('click', '.quick-view-btn', function() { //console.log('Botón Quick View clicado'); // Log para verificar el clic var productId = $(this).data('product-id'); //console.log('ID del producto:', productId); // Log para verificar el ID del producto $('#quick-view-popup').fadeIn(); //console.log('Popup Quick View mostrado'); // Log para verificar que el popup se muestra $.ajax({ type: 'POST', url: ajax_url, // Asegúrate de que ajax_url está correctamente definido data: { action: 'obtener_info_producto', // Asegúrate de que este nombre coincide con el manejador en PHP product_id: productId }, success: function(response) { //console.log('Respuesta AJAX exitosa:', response); // Log para verificar la respuesta del servidor $('#quick-view-popup').addClass('mostrar'); $('#quick-view-popup').removeClass('ocultar'); $('#quick-view-product-info').html(response); }, error: function(jqXHR, textStatus, errorThrown) { console.error("Error en la solicitud AJAX:", textStatus, errorThrown); console.error("Detalles del error:", jqXHR.responseText); // Log para verificar detalles del error alert("Hubo un problema al cargar la información del producto. Por favor, intenta nuevamente."); } }); });
This is the function. It works fine except calling the hook element:
/** Quick view */ function obtener_info_producto() { if (isset($_POST['product_id'])) { $product_id = intval($_POST['product_id']); //og("ID del producto recibido: " . $product_id); // Log para verificar el ID del producto $producto = wc_get_product($product_id); //error_log("Producto obtenido: " . print_r($producto, true)); // Log para verificar el producto $produccion_estimada = get_field('produccion_estimada', $product_id); if ($producto) { // Generar el contenido del popup ?> <div id="quick-view-product" class="quick-view-product"> <div class="product-images"> <img id="main-product-image" src="<?php echo wp_get_attachment_url($producto->get_image_id()); ?>" alt="<?php echo $producto->get_name(); ?>"> <?php $attachment_ids = $producto->get_gallery_image_ids(); if ($attachment_ids) { echo '<div class="product-gallery">'; echo '<img class="gallery-image" src="' . wp_get_attachment_url($producto->get_image_id()) . '" alt="' . $producto->get_name() . '">'; foreach ($attachment_ids as $attachment_id) { echo '<img class="gallery-image" src="' . wp_get_attachment_url($attachment_id) . '" alt="' . $producto->get_name() . '">'; } echo '</div>'; } ?> </div> <div class="product-details"> <h3><?php echo $producto->get_name(); ?></h3> <p class="precio-producto"><?php echo $producto->get_price_html(); ?></p> <?php if ($producto->get_stock_status() === 'instock'): ?> <p class="stock-disponible">Edición limitada. Solo se elaborarán <?php echo esc_html($produccion_estimada); ?> cajas de 9 unidades. <br>¡Reserva ya tu parte de la cosecha!</p> <?php else: ?> <p class="stock-agotado">Agotado</p> <?php endif; ?> <?php $produccion_estimada = get_field('produccion_estimada', $product_id); ?> <div class="pre-ventas-bar"> <?php $produccion_estimada = get_field('produccion_estimada', $product_id); ?> <div class="pre-ventas-bar-fill" style="width: <?php echo (( $produccion_estimada - $producto->get_stock_quantity()) / $produccion_estimada) * 100; ?>%;"></div> </div> <p><?php echo $producto->get_description(); ?></p> <!--<p><span class="subtitle-popup">Producción Estimada:</span> <?php //echo get_field('produccion_estimada', $product_id); ?></p>--> <p><span class="subtitle-popup">Fecha Estimada de Plantación:</span> <?php echo get_field('fecha_estimada_plantacion', $product_id); ?></p> <p><span class="subtitle-popup">Fecha de Entrega Estimada:</span> <?php echo get_field('fecha_de_entrega_estimada', $product_id); ?></p> <div class="contenedor acordeon"> <?php $product_id = isset($_POST['product_id']) ? intval($_POST['product_id']) : 0; /*error_log('Popup Product ID: ' . $product_id); error_log('Post Exists: ' . (get_post($product_id) ? 'Yes' : 'No')); error_log('ACF Fields: ' . print_r(get_fields($product_id), true));*/ // Validate $product_id if ($product_id && get_post($product_id)) { // Set up a WP_Query for the specific product_id $query = new WP_Query([ 'p' => $product_id, 'post_type' => 'any', // Adjust to 'product' if using WooCommerce, etc. 'posts_per_page' => 1, ]); error_log('Query Results: ' . print_r($query->posts, true)); // Log the query results if ($query->have_posts()) : while ($query->have_posts()) : $query->the_post(); ?> <div class="contenedor acordeon"> <?php do_action('hook_acordeon', $product_id); ?> </div> <?php endwhile; // Reset post data to avoid conflicts wp_reset_postdata(); else : echo '<p>Product not found.</p>'; endif; } else { echo '<p>Invalid product ID.</p>'; } ?> </div> </div> </div> <?php } else { error_log("Producto no encontrado: " . $product_id); // Log para verificar si el producto no se encuentra } wp_die(); } else { error_log("Product ID no establecido en la solicitud AJAX"); // Log para verificar si el ID del producto no está establecido } } add_action('wp_ajax_obtener_info_producto', 'obtener_info_producto'); add_action('wp_ajax_nopriv_obtener_info_producto', 'obtener_info_producto');
If you need to access the entire code:
Thanks a lot.
-
The GP Element – does it have its display rules set ? eg.
Entire site
so it fires anywhere
And if you add static content to the element – does it show up ? -
Guillermo
Mmm, it looks like it’s not showing up static content either.
On the other hand, the static contect it’s showing up in single-content.
We’re close.
-
So, what is the location you set for the element?
-
Guillermo
Hi,
sorry, on the last comment I posted anbut I didn´t show up.
Please check it here:
-
In your
obtener_info_producto
within the loop you have:<div class="contenedor acordeon"> <?php do_action('hook_acordeon', $product_id); ?> </div>
Does the
<div class="contenedor acordeon">
output ?
If so then the hook may need object buffering. Try wrapping thedo_action('hook_acordeon', $product_id);
withob_start()
andob_get_clean()
NOTE: the
$product_id
should not be required in the do_action as the Loop is providing the post context. And the post meta fetching done by GB Dynamic Data will only work with the post context, it won’t consume that variable in the hook. -
Guillermo
Hi,
I’ve uploaded the changes and still not working.I’ve added a
echo "Accion hook_acordeon";
so you can see that the div is being printed, but not the hook.
Thanks for your effort.
-
Can you see the Element being called on the page? You should see it in the Admin Bar > Elements menu.
- You must be logged in to reply to this topic.