Error with get_price (and others) in self-written plugin to show price

The error

Is coming from the file:

/wp-content/plugins/woocommerce-display-various/display_various.php

Line 180.

Disable the plugin ‘woocommerce-display-various’ and check if the problem still exists.


Your code

Why are you using output buffering (ob_start())? Furthermore you’re not using it correctly.

There’s alot to improve on your code…

See my changes:

add_action('init','add_custom_price_shortcodes');

function add_custom_price_shortcodes() {
  if ( class_exists( 'woocommerce' ) ) {
    add_shortcode('display_price', 'display_price_shortcode');
    add_shortcode('display_price_no_style', 'display_price_no_style_shortcode');
  }
}

function display_price_shortcode() {
  global $post;

  if(get_post_type($post->ID) == 'product'){
    return price_shortcode_display_price($post->ID, 'with_style');
  } else {
    return "";
  }
}

function display_price_no_style_shortcode() {
  global $post;

  if(get_post_type($post->ID) == 'product'){
    return price_shortcode_display_price($post->ID, 'no_style');
  } else {
    return "";
  }
}

function price_shortcode_display_price($post_id, $type="no_style") {

  $product = wc_get_product($post_id);

  if($product) {

    $derpreis = $product->get_price();

    if($derpreis > 0 ) {
      if( $type == 'no_style') {
        return $product->get_price_html();
      }
      if( $type == 'with_style') {
        return '<span class="displayprice">'. $product->get_price_html() . '</span>';
      }
    } else {
      return 'Kein Preis verfügbar';
    }
  } else {
    return 'Kein Preis verfügbar';
  }
}

Regards, Bjorn