最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

actions - do_action doesn't trigger if it's in a template that gets loaded via REST endpoint

programmeradmin1浏览0评论

i'm building a single page application using woocommerce and custom REST endpoints to get template parts and load them into the browser ... one endpoint is getting content-single-product.php template which loads single product details below is the code of the template

<?php
do_action( 'woocommerce_after_single_product_summary' );
?>

and here is the code that get's the product template and send back to javascript

/**
* Get Single Product
*
* @param int $product_id product id
* @return string|boolean html for single page
*/
function nh_get_product( $product_id ) {
    global $product;
    $output_html;

    ob_start();
    $product = wc_get_product($product_id);
    get_template_part('woocommerce/content-single-product');
    $output_html = ob_get_contents();
    ob_end_clean();

    return $output_html;

}


public function get_item( $request ) {
    $product_id = $request->get_param('p_id');

    if ( function_exists( 'nh_get_product' ) && $product_id ) {
      $output_html = nh_get_product( $product_id );
      if ( !empty($output_html) ) {
        $data = array( 'result' =>  $output_html );
        return new WP_REST_Response( $data, 200 );
      }
    }

    return new WP_Error( 'not-found', 'cannot find product', array( 'status' => 500 ) );
  }

the endpoint is working fine and sending back the html to the javascript, the problem is in do_action( 'woocommerce_after_single_product_summary' ); it does not trigger and does not throw any errors ... i replaced it with basic action hook that echo 'test' just for testing and still did not trigger .. im guessing do_action does not work inside ob_start();

i could just replace the do_action with direct calls to whatever the hook was doing and it will work i'm guessing ... but i just wanted to keep consistent with woocommerce templating system so i avoid any future big conflicts with the updates

EDIT: i removed the part of the HTML content in content-single-product.php that runs fine to ease in reading my question

发布评论

评论列表(0)

  1. 暂无评论