Firing a Woocommerce hook using a shortcode in post content

165 Views Asked by At

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.

1

There are 1 best solutions below

3
Scuzzy On BEST ANSWER

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');