phpwordpresswoocommerceoutput-buffering

Firing a Woocommerce hook using a shortcode in post content


I am trying to assign the action hook woocommerce_single_product_summary to a shortcode so that, rather than do_action being used in a fixed place in the template, the end-user can move the whole single_product_summary section of the page around freely within a layout they've created in Gutenberg.

I have the following in functions.php:

    function getsummary_shortcode( $atts ) {
    ob_start();
    do_action( 'woocommerce_single_product_summary' );
    $woocommerce_single_product = ob_get_clean();
    return $woocommerce_single_product;
}

add_shortcode('getsummary','getsummary_shortcode');

However, this seems to output the single_product_summary content in an infinite loop.

Is it actually possible to do this? I have found a few posts here trying to do something vaguely similar to this, but none trying to do quite what I'm doing.


Solution

  • You may need to deregister, and reregister your getsummary shortcode within your function callback to prevent it being called by the woocommerce_single_product_summary hook

    function getsummary_shortcode( $atts ) {
        remove_shortcode('getsummary');
        ob_start();
        do_action( 'woocommerce_single_product_summary' );
        $woocommerce_single_product = ob_get_clean();
        add_shortcode('getsummary','getsummary_shortcode');
        return $woocommerce_single_product;
    }
    
    add_shortcode('getsummary','getsummary_shortcode');