Are you a GenerateCustomer?

Do you have an active GP Premium or GenerateBlocks Pro license key?

Create a GenerateSupport account for GeneratePress and GenerateBlocks support in one dedicated place.

Create an account
Already have a GenerateSupport account? Login

Just browsing?

Feel free to browse the forums. Support for our free versions is provided on WordPress.org (GeneratePress, GenerateBlocks).

Want to become a premium user? Learn more below.

How to simplify code for multiple block hooks

  • Hi there,

    I appreciate your help. I’ve resolved several problems thanks to this forum.

    I’d like to control the visibility of a survey form based on the login status, so I followed the code from the page below. I’m really happy that it’s working well.
    https://generatepress.com/forums/topic/hooks-related-question/#post-2170598

    Additionally, if more forms are added, I’ll have to repeat the process.
    Is there a way to simplify this by adding attributes to the shortcode or something?

    For example, my current code is:

    function display_form_fmh_001_for_user($atts, $content = null) {
    ob_start();
    do_action(‘block_form_fmh_001_for_user’);
    return ob_get_clean();
    }
    add_shortcode(‘hm_form_fmh_001_for_user’, ‘display_form_fmh_001_for_user’);

    I created a Block Hook named “block_form_fmh_001_for_user” and added this code through snippet.
    Then, I add a shortcode block [hm_form_fmh_001_for_user] to a page.

  • Hi there,

    You could do something like this:

    add_shortcode('portable_hook', function($atts){
    	ob_start();
            $atts = shortcode_atts( array(
                'hook_name' => 'no foo'
            ), $atts, 'portable_hook' );
    		do_action($atts['hook_name']);
    	return ob_get_clean();
    });

    The snippet above registers a new shortcode called portable_hook. The shortcode takes an attribute hook_name that specifies which hook to trigger.

    You can then use the shortcode like this in your content:

    
    [portable_hook hook_name="block_form_fmh_001_for_user"]
    [portable_hook hook_name="block_form_fmh_002_for_user"]
    [portable_hook hook_name="block_form_fmh_003_for_user"]
    

    This way, the specified hook will be executed at the location where you place each shortcode.

  • Thank you, Alvind. The code is perfect and beautiful!

  • You’re welcome!

Viewing 4 posts - 1 through 4 (of 4 total)
  • You must be logged in to reply to this topic.