How to test for a class (from a plugin) in functions.php

I’ve added various code changes to functions.php. Many of them depend on certain plug-ins being active, as they refer to classes defined by those plug-ins.

If the plug-ins are disabled, it will cause a 500 server error, due to the respective classes not being found.

Is there a way to first test for a class?

For example, the following function relies on a class from a WooCommerce extension.

// Add prices to variations
add_filter( ‘woocommerce_variation_option_name’, ‘display_price_in_variation_option_name’ );
function display_price_in_variation_option_name( $term ) {
global $wpdb, $product;
$result = $wpdb->get_col( “SELECT slug FROM {$wpdb->prefix}terms WHERE name = ‘$term'” );
$term_slug = ( !empty( $result ) ) ? $result[0] : $term;
$query = “SELECT postmeta.post_id AS product_id FROM {$wpdb->prefix}postmeta AS postmeta LEFT JOIN {$wpdb->prefix}posts AS products ON ( products.ID = postmeta.post_id ) WHERE postmeta.meta_key LIKE ‘attribute_%’ AND postmeta.meta_value = ‘$term_slug’ AND products.post_parent = $product->id”;
$variation_id = $wpdb->get_col( $query );
$parent = wp_get_post_parent_id( $variation_id[0] );
if ( $parent > 0 ) { $_product = new WC_Product_Variation( $variation_id[0] );
//$itemPrice = ‘ ‘ . strip_tags (woocommerce_price( $_product->get_price() ));
//this is where you can actually customize how the price is displayed
//return $term . ‘ (‘ . $itemPrice . ‘)’;
$curr = get_woocommerce_currency_symbol(); //get_option(‘woocommerce_currency’);
$regular_price = trim($_product->regular_price);
$sales_price = trim($_product->sale_price);
if($sales_price == ” || $regular_price == $sales_price) { return $term . ‘ (‘ . $curr.$regular_price . ‘)’; }
else { return $term . ‘ (Was ‘ . $curr.$regular_price . ‘, Now ‘ . $curr.$sales_price . ‘)’; }
} return $term;
}

global $woocommerce;
$product_variation = new WC_Product_Variation($_POST[‘variation_id’]);
$regular_price = $product_variation->regular_price;

But if the relevant plug-in is disabled, PHP will generate the error, “PHP message: PHP Fatal error: Uncaught Error: Class ‘WC_Product_Variation’ not found in … /functions.php:266

So I need to first test if WC_Product_Variation is defined before running this function.

Read more here:: How to test for a class (from a plugin) in functions.php

Leave a Reply

Your email address will not be published. Required fields are marked *