Home > Software engineering >  Overriding WooCommerce template part creates an infinite loop
Overriding WooCommerce template part creates an infinite loop

Time:12-09

I have created a function that overrides WooCommerce template-part for single-product in my custom plugin, if a certain meta value is met. But when there is a related product with the custom template-part it just goes to a infinite loop because it loads the custom template inside related products too. how can I avoid loading template-part in related products?

function override_woo_template_part($template, $slug, $name) {

  global $post;

  $product = wc_get_product($post->ID);
  $myplugin_type = $product->get_meta('_myplugin_type');
  $path = '';

  if ($name && !empty($myplugin_type) && $myplugin_type != 'default') {

    $template_directory = myplugin_directory_path() . '/woocommerce/';
    $path = $template_directory . "{$slug}-{$myplugin_type}.php";

  }

  return file_exists($path) ? $path : $template;

}
add_filter('wc_get_template_part', 'override_woo_template_part', 10, 3);

CodePudding user response:

As @VijayHardaha suggested, adding validation to only load template-part if filename $name is equal to single-product worked.

function override_woo_template_part($template, $slug, $name) {

  global $post;

  $product = wc_get_product($post->ID);
  $myplugin_type = $product->get_meta('_myplugin_type');
  $path = '';

  if ($name && $name == 'single-product' && !empty($myplugin_type) && $myplugin_type != 'default') {

    $template_directory = myplugin_directory_path() . '/woocommerce/';
    $path = $template_directory . "{$slug}-{$myplugin_type}.php";

  }

  return file_exists($path) ? $path : $template;

}
add_filter('wc_get_template_part', 'override_woo_template_part', 10, 3);
  • Related