Site logo

Archived topic

Echoing a Generateblock in a custom function

9 replies · Started by Marcel on October 30, 2020

Viewing posts 1–10 of 10

Hello
Question: I use a code snippet on my cart page to show a specific message for my customers.
Is it possible to insert a specific block (made with Generateblocks) in a custom function?

Hmmm, this sounds interesting and it might work. But where should I insert my custom function?
As you can see on my code snippet (which works fine if I add it in my function.php), I add an action and a function:

add_action( 'woocommerce_proceed_to_checkout', 'wpdesk_cart_message' );
/**
 * Add a specific message to WooCommerce cart page
 *
 */
function wpdesk_cart_message() {
	echo '<p>This is a specific message</p>';
}

If all you want is to display a block in that location then you do not need the function.
Simply create the Block Element and set the Hook as i explained above.

Okay, I tried and it works if I want to show the same Block Element for doesn't matter what products are in the cart, and understand I do not need a function for that.

However, if I would like to add some conditions, for example, to show the Block Element "A" if product A is in the cart or to show the Block Element "B" if product B is in the cart, do you think it is possible? Of course, I need to use a function here.

I specify I know how to manipulate conditions (if, elseif and so on) in a function, but I don't know how I could use the blocks in this case.

You could use the generate_block_element_display filter to selectively display which block element for example:

add_filter( 'generate_block_element_display', function( $display, $element_id ) {
  if ( 123 === $element_id && is_my_custom_condition() ) {
     $display = false;
  }

  return $display;
}, 10, 2 );

the 123 is the Block Elements ID.
In the example this would remove the Block element if:

a. its ID matches
AND
b. your custom condition is met.

David,

The filter what are you talking about (generate_block_element_display) should be inserted on my function.php, right?

Thats correct.

Okay, and in my Block Element I have to add in the Custom Hook name:
generate_block_element_display, is it correct?

No in your Block Element you add the custom hook name which is the one you had in your add_action:

woocommerce_proceed_to_checkout

Create your various block elements all with the same hook.
You should see all blocks being displayed on the checkout.

Then the add_filter function i provided here:

https://generatepress.com/forums/topic/echoing-a-generateblock-in-a-custom-function/#post-1511311

Goes in your functions PHP.
As long as your custom condition is valid, it will remove the Block element with the same ID.

This archived topic is closed to new replies.